repo
stringlengths
5
75
commit
stringlengths
40
40
message
stringlengths
6
18.2k
diff
stringlengths
60
262k
solidsnack/shuffle
58b49b9da7e6a70e136a05e17a9d4d67cb0a1b83
Does HTML but does not actually shuffle...
diff --git a/ShuffleBingoHTML.hs b/ShuffleBingoHTML.hs index 6336afc..1234d9c 100755 --- a/ShuffleBingoHTML.hs +++ b/ShuffleBingoHTML.hs @@ -1,91 +1,108 @@ #!/usr/bin/env runhaskell import Data.Word import qualified Data.List as List import qualified Data.Set as Set import qualified Data.ByteString.Lazy as Bytes (hPutStr) import qualified Data.ByteString.Lazy.Char8 as Bytes import qualified Data.Char as Char import Control.Applicative import System.Environment import System.IO import System.IO (stdin, stderr, stdout) import System.Exit import Text.Printf import qualified Codec.Archive.Tar as Tar import qualified Codec.Archive.Tar.Entry as Tar n = 24 usage name = unlines [ "USAGE: " ++ name ++ " count < some-lines" , "" , " Shuffles lines into groups of " ++ show n ++ " unique lines, then puts them into" , " an HTML table that is 5x5 and has an empty square in the middle." , " You specify $count to get only that many files in the output. The" , " is a streaming TAR archive." ] main = do name <- getProgName go name go name = do parsed <- digitize <$> getArgs case parsed of Left s -> fail s Right count -> do choices <- Set.fromList . no_empty . Bytes.lines <$> b_in if Set.size choices < n then fail "Not enough lines to choose from." else do (Bytes.hPutStr stdout . tar (name_nums count)) (render <$> block_out count choices) where tar names contents = Tar.write (tars dir' names contents) dir = "shuffle-bingo-html-output" Right dir' = Tar.toTarPath True "shuffle-bingo-html-output" name_nums how_many = name <$> [0..(how_many-1)] where name num = p where Right p = Tar.toTarPath False (dir ++ "/" ++ printf (digits ++ ".html") num) digits = "%0" ++ (show . length . show) how_many ++ "d" no_empty = filter (not . Bytes.all Char.isSpace) fail s = do hPutStrLn stderr s hPutStrLn stderr "" hPutStrLn stderr (usage name) exitFailure b_in = Bytes.hGetContents stdin digitize :: [String] -> Either String Word digitize [s] = case reads s of [(i,"")] -> if i > 0 then Right i else Left "Non-positive." _ -> Left "Argument error." digitize _ = Left "Wrong number of args." +block_out :: Word -> Set.Set t -> [[t]] block_out choose choices = (combinations choose . Set.toList) choices where - combinations 0 _ = [ [] ] - combinations i a = [ y:ys | y:b <- List.tails a - , ys <- combinations (i-1) b ] - - -render = Bytes.unlines + combinations 0 _ = [[]] + combinations _ [] = [] + combinations k (x:xs) = map (x:) (combinations (k-1) xs) ++ combinations k xs + + +render texts = Bytes.unlines + [ Bytes.pack "<table> <tbody>" + , tr (pick [0..4]) + , tr (pick [5..9]) + , tr (pick [10..11] ++ [place_image] ++ pick [12..13]) + , tr (pick [14..18]) + , tr (pick [19..24]) + , Bytes.pack "</table> </tbody>" + ] + where + tr elems = Bytes.unlines ([Bytes.pack "<tr>"] ++ + (td <$> elems) + ++ [Bytes.pack "</tr>"]) + td text = Bytes.unwords + [Bytes.pack "<td>", text, Bytes.pack "</td>"] + pick = ((texts !!) <$>) + place_image = Bytes.pack "<!-- Place image here. -->" tars dir names contents = Tar.directoryEntry dir : [ Tar.fileEntry name content | name <- names | content <- contents ]
solidsnack/shuffle
cccf9817c1e30046c1874b0e68a7076465e05ded
Compiles, hurrah.
diff --git a/ShuffleBingoHTML.hs b/ShuffleBingoHTML.hs index 72bd311..6336afc 100755 --- a/ShuffleBingoHTML.hs +++ b/ShuffleBingoHTML.hs @@ -1,85 +1,91 @@ #!/usr/bin/env runhaskell -import System.IO (stdin, stderr, stdout) -import Control.Applicative +import Data.Word import qualified Data.List as List import qualified Data.Set as Set import qualified Data.ByteString.Lazy as Bytes (hPutStr) import qualified Data.ByteString.Lazy.Char8 as Bytes import qualified Data.Char as Char +import Control.Applicative import System.Environment import System.IO +import System.IO (stdin, stderr, stdout) import System.Exit +import Text.Printf import qualified Codec.Archive.Tar as Tar import qualified Codec.Archive.Tar.Entry as Tar n = 24 usage name = unlines [ "USAGE: " ++ name ++ " count < some-lines" , "" , " Shuffles lines into groups of " ++ show n ++ " unique lines, then puts them into" , " an HTML table that is 5x5 and has an empty square in the middle." , " You specify $count to get only that many files in the output. The" , " is a streaming TAR archive." ] main = do name <- getProgName go name go name = do parsed <- digitize <$> getArgs case parsed of Left s -> fail s Right count -> do choices <- Set.fromList . no_empty . Bytes.lines <$> b_in if Set.size choices < n then fail "Not enough lines to choose from." else do - tar_out (name_nums choices) (render <$> block_out count choices) + (Bytes.hPutStr stdout . tar (name_nums count)) + (render <$> block_out count choices) where - tar_out names = (Bytes.hPutStr . Tar.write . tars dir names) - Right dir = toTarPath True "shuffle-bingo-html-output" + tar names contents = Tar.write (tars dir' names contents) + dir = "shuffle-bingo-html-output" + Right dir' = Tar.toTarPath True "shuffle-bingo-html-output" name_nums how_many = name <$> [0..(how_many-1)] where name num = p where - Right p = toTarPath + Right p = Tar.toTarPath False (dir ++ "/" ++ printf (digits ++ ".html") num) digits = "%0" ++ (show . length . show) how_many ++ "d" no_empty = filter (not . Bytes.all Char.isSpace) fail s = do hPutStrLn stderr s hPutStrLn stderr "" hPutStrLn stderr (usage name) exitFailure b_in = Bytes.hGetContents stdin + digitize :: [String] -> Either String Word digitize [s] = case reads s of [(i,"")] -> if i > 0 then Right i else Left "Non-positive." _ -> Left "Argument error." digitize _ = Left "Wrong number of args." block_out choose choices = (combinations choose . Set.toList) choices where combinations 0 _ = [ [] ] - combinations i a = [ y:ys | y:b <- tails a + combinations i a = [ y:ys | y:b <- List.tails a , ys <- combinations (i-1) b ] render = Bytes.unlines tars dir names contents = Tar.directoryEntry dir : [ Tar.fileEntry name content | name <- names | content <- contents ] + diff --git a/shuffle-bingo.cabal b/shuffle-bingo.cabal index 34db659..e2e9e08 100644 --- a/shuffle-bingo.cabal +++ b/shuffle-bingo.cabal @@ -1,25 +1,26 @@ name : shuffle-bingo version : 0.0.0 license : BSD3 license-file : LICENSE author : Jason Dusek maintainer : [email protected] homepage : http://github.com/jsnx/JSONb/ synopsis : Bingo shuffler for 5MOF. description : Shuffles input into a bingo card for 5 Minutes of Fame. cabal-version : >= 1.6.0 build-type : Simple extra-source-files : README executable shuffle-bingo-html main-is : ShuffleBingoHTML.hs build-depends : base >= 2 && < 4 , tar >= 0.3.1.0 , bytestring >= 0.9 + , containers extensions : NoMonomorphismRestriction ParallelListComp
solidsnack/shuffle
02d148889b1658dfbd52470821dbe33e2ebc96e4
Cabalizing.
diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..23f293f --- /dev/null +++ b/LICENSE @@ -0,0 +1,28 @@ + + ©2009 Jason Dusek. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + . Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + . Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + . Names of the contributors to this software may not be used to endorse or + promote products derived from this software without specific prior written + permission. + + This software is provided by the contributors "as is" and any express or + implied warranties, including, but not limited to, the implied warranties of + merchantability and fitness for a particular purpose are disclaimed. In no + event shall the contributors be liable for any direct, indirect, incidental, + special, exemplary, or consequential damages (including, but not limited to, + procurement of substitute goods or services; loss of use, data, or profits; + or business interruption) however caused and on any theory of liability, + whether in contract, strict liability, or tort (including negligence or + otherwise) arising in any way out of the use of this software, even if + advised of the possibility of such damage. + diff --git a/ShuffleBingoHTML.hs b/ShuffleBingoHTML.hs new file mode 100755 index 0000000..72bd311 --- /dev/null +++ b/ShuffleBingoHTML.hs @@ -0,0 +1,85 @@ +#!/usr/bin/env runhaskell + + +import System.IO (stdin, stderr, stdout) +import Control.Applicative +import qualified Data.List as List +import qualified Data.Set as Set +import qualified Data.ByteString.Lazy as Bytes (hPutStr) +import qualified Data.ByteString.Lazy.Char8 as Bytes +import qualified Data.Char as Char +import System.Environment +import System.IO +import System.Exit + +import qualified Codec.Archive.Tar as Tar +import qualified Codec.Archive.Tar.Entry as Tar + + + + +n = 24 + + +usage name = unlines + [ "USAGE: " ++ name ++ " count < some-lines" + , "" + , " Shuffles lines into groups of " + ++ show n ++ " unique lines, then puts them into" + , " an HTML table that is 5x5 and has an empty square in the middle." + , " You specify $count to get only that many files in the output. The" + , " is a streaming TAR archive." + ] + + +main = do + name <- getProgName + go name + + +go name = do + parsed <- digitize <$> getArgs + case parsed of + Left s -> fail s + Right count -> do + choices <- Set.fromList . no_empty . Bytes.lines <$> b_in + if Set.size choices < n + then fail "Not enough lines to choose from." + else do + tar_out (name_nums choices) (render <$> block_out count choices) + where + tar_out names = (Bytes.hPutStr . Tar.write . tars dir names) + Right dir = toTarPath True "shuffle-bingo-html-output" + name_nums how_many = name <$> [0..(how_many-1)] + where + name num = p + where + Right p = toTarPath + (dir ++ "/" ++ printf (digits ++ ".html") num) + digits = "%0" ++ (show . length . show) how_many ++ "d" + no_empty = filter (not . Bytes.all Char.isSpace) + fail s = do + hPutStrLn stderr s + hPutStrLn stderr "" + hPutStrLn stderr (usage name) + exitFailure + b_in = Bytes.hGetContents stdin + digitize [s] = case reads s of + [(i,"")] -> if i > 0 then Right i else Left "Non-positive." + _ -> Left "Argument error." + digitize _ = Left "Wrong number of args." + + +block_out choose choices = (combinations choose . Set.toList) choices + where + combinations 0 _ = [ [] ] + combinations i a = [ y:ys | y:b <- tails a + , ys <- combinations (i-1) b ] + + +render = Bytes.unlines + + +tars dir names contents = Tar.directoryEntry dir : + [ Tar.fileEntry name content | name <- names | content <- contents ] + diff --git a/shuffle-bingo.cabal b/shuffle-bingo.cabal new file mode 100644 index 0000000..34db659 --- /dev/null +++ b/shuffle-bingo.cabal @@ -0,0 +1,25 @@ +name : shuffle-bingo +version : 0.0.0 +license : BSD3 +license-file : LICENSE +author : Jason Dusek +maintainer : [email protected] +homepage : http://github.com/jsnx/JSONb/ +synopsis : Bingo shuffler for 5MOF. +description : + Shuffles input into a bingo card for 5 Minutes of Fame. + + +cabal-version : >= 1.6.0 +build-type : Simple +extra-source-files : README + + +executable shuffle-bingo-html + main-is : ShuffleBingoHTML.hs + build-depends : base >= 2 && < 4 + , tar >= 0.3.1.0 + , bytestring >= 0.9 + extensions : NoMonomorphismRestriction + ParallelListComp +
solidsnack/shuffle
d39ee831bbe5e3f22f23a1450ec54072e87ad816
First version.
diff --git a/Shuffle.hs b/Shuffle.hs new file mode 100755 index 0000000..84c29d4 --- /dev/null +++ b/Shuffle.hs @@ -0,0 +1,56 @@ +#!/usr/bin/env runhaskell + + +import System.IO (stdin, stderr, stdout) +import Control.Applicative +import qualified Data.List as List +import qualified Data.Set as Set +import qualified Data.ByteString.Lazy as Bytes (hPutStr) +import qualified Data.ByteString.Lazy.Char8 as Bytes +import qualified Data.Char as Char +import System.Environment +import System.IO +import System.Exit + + + + +usage name = unlines + [ "USAGE: " ++ name ++ " n < some-lines" + , "" + , " Shuffles lines into groups of lines $n unique lines." + ] + + +main = do + name <- getProgName + go name + + +go name = do + parsed <- digitize <$> getArgs + case parsed of + Left s -> fail s + Right i -> do + choices <- Set.fromList . no_empty . Bytes.lines <$> b_in + if Set.size choices < i + then fail "Not enough lines to choose from." + else do + (Bytes.hPutStr stdout . Bytes.unlines + . (Bytes.unlines . take i <$>) + . List.permutations + . Set.toList) choices + where + no_empty = filter (not . Bytes.all Char.isSpace) + fail s = do + hPutStrLn stderr s + hPutStrLn stderr "" + hPutStrLn stderr (usage name) + exitFailure + b_in = Bytes.hGetContents stdin + digitize [s] = case reads s of + [(i,"")] -> if i > 0 then Right i else Left "Non-positive." + _ -> Left "Argument error." + digitize _ = Left "Wrong number of args." + +
solidsnack/shuffle
9bcf03464c6326db99ddc6cefc9d9d15c11f0be2
First!!1!!!!!11!
diff --git a/README b/README new file mode 100644 index 0000000..e69de29
JasonMiesionczek/As3toHaxe
725f1e3d986fc64825f29dea7201b8a0770f8f6d
more improvements to parser, now correctly ignores most comments.
diff --git a/bin/As3toHaxe.n b/bin/As3toHaxe.n index 1d0aaee..29ddc05 100644 Binary files a/bin/As3toHaxe.n and b/bin/As3toHaxe.n differ diff --git a/run.bat b/run.bat index c018153..9f93af7 100644 --- a/run.bat +++ b/run.bat @@ -1,4 +1,4 @@ @echo off cd bin -neko As3toHaxe.n d:/development/ffilmation d:/development/as3tohaxe_output +neko As3toHaxe.n d:/development/ffilmation d:/development/isometric_test/src pause diff --git a/src/net/interaxia/as3tohaxe/Main.hx b/src/net/interaxia/as3tohaxe/Main.hx index 7cb9d22..3f659a5 100644 --- a/src/net/interaxia/as3tohaxe/Main.hx +++ b/src/net/interaxia/as3tohaxe/Main.hx @@ -1,121 +1,120 @@ package net.interaxia.as3tohaxe; import neko.FileSystem; import neko.io.File; import neko.io.FileOutput; import neko.io.Path; import neko.Lib; import neko.Sys; import net.interaxia.as3tohaxe.api.AllTypes; -import net.interaxia.as3tohaxe.api.CustomTypes; import net.interaxia.as3tohaxe.api.FlashAPI; import net.interaxia.as3tohaxe.inspector.FileInspector; import net.interaxia.as3tohaxe.translator.Translator; /** * ... * @author Jason Miesionczek */ class Main { static function main() { var inputPath:String = ""; var outputPath:String = ""; if (Sys.args().length == 0) { inputPath = Sys.getCwd(); } else if (Sys.args().length == 2) { inputPath = Sys.args()[0]; outputPath = Sys.args()[1]; } try { if (!FileSystem.exists(outputPath)) { FileSystem.createDirectory(outputPath); } } catch (msg:String) { Lib.println("There was an error creating the specified output directory. Ensure the parent drive/directory exists and you have write permissions to it."); return; } Lib.println("Input path: " + inputPath); Lib.println("Output path: " + outputPath); Lib.println("Scanning input folder..."); var cpscanner:ClassPathScanner = new ClassPathScanner(inputPath); cpscanner.scan(); var haxeFiles:List<HaxeFile> = new List<HaxeFile>(); AllTypes.getInstance().initAllTypes(); Lib.println("Inspecting files..."); for (f in cpscanner.filesToParse) { var fi:FileInspector = new FileInspector(f); var hf:HaxeFile = fi.inspect(); haxeFiles.add(hf); } Lib.println("Collecting type information..."); //CustomTypes.getInstance().setupMatches(); //Translator.initTypeRegs(); for (f in haxeFiles) { Translator.compileTypes(f); } Lib.println("Translating files..."); for (f in haxeFiles) { var t:Translator = new Translator(f); t.translate(); } Lib.println("Generating output files..."); generateOutputFiles(haxeFiles, outputPath); Lib.println(haxeFiles.length + " files converted."); } static function generateOutputFiles(files:List < HaxeFile > , output:String) { for (file in files) { var fileName:String = Path.withoutDirectory(Path.withoutExtension(file.fullPath)); - if (CustomTypes.getInstance().matches.exists(fileName)) { + if (AllTypes.getInstance().getTypeByOrigName(fileName, false)!=null) { var newfileName:String = AllTypes.getInstance().getTypeByOrigName(fileName, false).normalizedName;//CustomTypes.getInstance().matches.get(fileName); file.fullPath = StringTools.replace(file.fullPath, fileName, newfileName); } var fileOutputPath:String = output; if (file.filePackage.indexOf(".") >= 0) { var packageParts:Array < String > = file.filePackage.split("."); fileOutputPath = fileOutputPath + "/" + packageParts.join("/"); createOutputDirs(packageParts, output); } fileOutputPath += "/" + StringTools.replace(Path.withoutDirectory(file.fullPath), ".as", ".hx"); var fout:FileOutput = File.write(fileOutputPath, false); for (line in file.lines) { fout.writeString(line+"\n"); } fout.close(); } } static function createOutputDirs(parts:Array < String > , outputPath:String):Void { var currentPath:String = outputPath; for (p in parts) { currentPath += "/" + p; if (!FileSystem.exists(currentPath)) { FileSystem.createDirectory(currentPath); } } } } \ No newline at end of file diff --git a/src/net/interaxia/as3tohaxe/api/CustomTypes.hx b/src/net/interaxia/as3tohaxe/api/CustomTypes.hx deleted file mode 100644 index bd4ae5b..0000000 --- a/src/net/interaxia/as3tohaxe/api/CustomTypes.hx +++ /dev/null @@ -1,79 +0,0 @@ -/** - * ... - * @author Jason Miesionczek - */ - -package net.interaxia.as3tohaxe.api; - -class CustomTypes { - - private static var _instance:CustomTypes; - public static function getInstance():CustomTypes { - if (_instance == null) { - _instance = new CustomTypes(); - } - - return _instance; - } - - public var types(default, default): List<String>; - public var matches(default, null): Hash<String>; - - private function new() { - types = new List<String>(); - matches = new Hash<String>(); - - matches.set("int", "Int"); - matches.set("void", "Void"); - matches.set("Number", "Float"); - matches.set("Array", "Array<Dynamic>"); - matches.set("Boolean", "Bool"); - } - - public function setupMatches():Void { - for (stype in getShortNames()) { - matches.set(stype, stype.charAt(0).toUpperCase() + stype.substr(1)); - } - } - - public function getTypeNormalized(originalName:String):String { - for (t in types) { - if (t == originalName) { - var idx:Int = t.lastIndexOf("."); - if (idx >= 0) { - var type:String = t.substr(idx + 1); - var orig:String = type; - type = type.charAt(0).toUpperCase() + type.substr(1); - return StringTools.replace(t, orig, type); - } - } - } - - return originalName; - } - - public function getFullTypeByName(name:String):String { - for (t in types) { - if (StringTools.endsWith(t, name)) { - return getTypeNormalized(t); - } - } - - return name; - } - - public function getShortNames():List < String > { - var snames:List<String> = new List<String>(); - for (t in types) { - var idx:Int = t.lastIndexOf("."); - if (idx >= 0) { - snames.add(t.substr(idx+1)); - } else { - snames.add(t); - } - } - - return snames; - } - -} \ No newline at end of file diff --git a/src/net/interaxia/as3tohaxe/inspector/FileInspector.hx b/src/net/interaxia/as3tohaxe/inspector/FileInspector.hx index e8247d0..1892f37 100644 --- a/src/net/interaxia/as3tohaxe/inspector/FileInspector.hx +++ b/src/net/interaxia/as3tohaxe/inspector/FileInspector.hx @@ -1,97 +1,96 @@ /** * ... * @author Jason Miesionczek */ package net.interaxia.as3tohaxe.inspector; import neko.io.FileInput; import neko.io.File; import haxe.io.Eof; import neko.Lib; import net.interaxia.as3tohaxe.api.AllTypes; -import net.interaxia.as3tohaxe.api.CustomTypes; import net.interaxia.as3tohaxe.api.ObjectType; import net.interaxia.as3tohaxe.HaxeFile; class FileInspector { private var _inputFile:String; private var _fileObject:FileInput; private var _lines:List<String>; private var _package:String; private var _types:List<String>; private var _hf:HaxeFile; public function new(file:String) { _inputFile = file; _lines = new List<String>(); _types = new List<String>(); } public function inspect():HaxeFile { _hf = new HaxeFile(); _hf.fullPath = _inputFile; _fileObject = File.read(_inputFile, false); try { while (true) { if (_fileObject.eof()) break; var l:String = _fileObject.readLine(); _lines.add(l); _hf.lines.push(l); } } catch (ex:Eof) {} _fileObject.close(); detectPackage(); detectClasses(); detectInterfaces(); return _hf; } private function detectPackage():Void { var packagePattern = ~/package\s+([a-z.]+)/; for (line in _lines) { if (packagePattern.match(line)) { _package = packagePattern.matched(1); _hf.filePackage = _package; return; } } _package = ""; } private function detectClasses():Void { var classPattern = ~/public\s+class\s+(\w+)/; for (line in _lines) { if (classPattern.match(line)) { var objType:ObjectType = new ObjectType(); objType.typePackage = _package; objType.originalName = classPattern.matched(1); objType.normalizeName(); AllTypes.getInstance().types.add(objType); } } } private function detectInterfaces():Void { var interfacePattern = ~/public\s+interface\s+(\w+)/; for (line in _lines) { if (interfacePattern.match(line)) { var objType:ObjectType = new ObjectType(); objType.typePackage = _package; objType.originalName = interfacePattern.matched(1); objType.normalizeName(); AllTypes.getInstance().types.add(objType); } } } } \ No newline at end of file diff --git a/src/net/interaxia/as3tohaxe/translator/Translator.hx b/src/net/interaxia/as3tohaxe/translator/Translator.hx index 30bdc4f..905d16f 100644 --- a/src/net/interaxia/as3tohaxe/translator/Translator.hx +++ b/src/net/interaxia/as3tohaxe/translator/Translator.hx @@ -1,253 +1,372 @@ /** * ... * @author Jason Miesionczek */ package net.interaxia.as3tohaxe.translator; import neko.io.FileInput; import neko.io.File; import haxe.io.Eof; import neko.Lib; -import net.interaxia.as3tohaxe.api.CustomTypes; + import net.interaxia.as3tohaxe.api.FlashAPI; import net.interaxia.as3tohaxe.api.ObjectType; import net.interaxia.as3tohaxe.HaxeFile; import net.interaxia.as3tohaxe.api.AllTypes; class Translator { private var _fileObject:FileInput; private var _lines:Array<String>; private var _output:List<String>; private var _hf:HaxeFile; private var _foundPackage:Bool; private var _currentLine:Int; private static var _typeRegs:List<EReg>; private static var _typeRegsFlash:List<EReg>; - + private static var _commentLines:List<Int>; public function new(inputFile:HaxeFile) { _lines = new Array<String>(); _output = new List<String>(); _hf = inputFile; for (l in inputFile.lines) { _lines.push(l); } } public static function compileTypes(f:HaxeFile):Void { - for (line in f.lines) { + _commentLines = new List<Int>(); + var _withinBlockComment:Bool = false; + for (line in 0...f.lines.length) { + var tempLine:String = f.lines[line]; + + if (isSingleLineComment(tempLine)) { + //newLines.push(tempLine); + _commentLines.add(line); + Lib.println(tempLine); + continue; + } + + if (isStartOfComment(tempLine)) { + _withinBlockComment = true; + //newLines.push(tempLine); + _commentLines.add(line); + Lib.println(tempLine); + continue; + } + + if (_withinBlockComment && isEndOfComment(tempLine)) { + _withinBlockComment = false; + //newLines.push(tempLine); + _commentLines.add(line); + Lib.println(tempLine); + continue; + } + + if (_withinBlockComment) { + //newLines.push(tempLine); + _commentLines.add(line); + Lib.println(tempLine); + continue; + } + } + + for (line in 0...f.lines.length) { checkForTypes(line, f); // this will build the new list of imports } } public function translate():Void { //Lib.println("Translating "+_hf.fullPath+"..."); _foundPackage = false; var packagePos:Int = -1; + var _withinBlockComment:Bool = false; var newLines:Array<String> = new Array<String>(); for (line in 0..._lines.length) { _currentLine = line; var tempLine:String = _lines[line]; + + if (isSingleLineComment(tempLine)) { + newLines.push(tempLine); + Lib.println(tempLine); + continue; + } + + if (isStartOfComment(tempLine)) { + _withinBlockComment = true; + newLines.push(tempLine); + Lib.println(tempLine); + continue; + } + + if (_withinBlockComment && isEndOfComment(tempLine)) { + _withinBlockComment = false; + newLines.push(tempLine); + Lib.println(tempLine); + continue; + } + + if (_withinBlockComment) { + newLines.push(tempLine); + Lib.println(tempLine); + continue; + } + if (!_foundPackage) { tempLine = convertPackage(tempLine); } if (_foundPackage && packagePos < 0) { packagePos = line; } tempLine = removeImports(tempLine); tempLine = convertClassName(tempLine); + tempLine = removePublicFromClass(tempLine); tempLine = convertInterfaceName(tempLine); tempLine = convertConstToVar(tempLine); tempLine = convertTypes(tempLine); tempLine = convertConstructorName(tempLine); tempLine = convertForLoop(tempLine); - + tempLine = addSemiColon(tempLine); //_lines[line] = tempLine; newLines.push(tempLine); } var tempLines:Array<String> = newLines; tempLines.reverse(); for (line in 0...tempLines.length) { var temp:String = StringTools.ltrim(tempLines[line]); if (StringTools.startsWith(temp, "}")) { tempLines = tempLines.slice(line+1); break; } } tempLines.reverse(); newLines = tempLines; // insert the new import statements just below the package definition. for (imp in _hf.imports) { var impStr:String = " import " + imp + ";"; newLines.insert(packagePos + 1, impStr); } _hf.lines = newLines; } + private static function isSingleLineComment(input:String):Bool { + var temp:String = StringTools.ltrim(input); + var temp2:String = StringTools.rtrim(input); + if (StringTools.startsWith(temp, "//")) { + return true; + } + + if (StringTools.startsWith(temp, "/*") && StringTools.endsWith(temp2, "*/")) { + return true; + } + + return false; + } + + private static function isStartOfComment(input:String):Bool { + var temp:String = StringTools.ltrim(input); + if (StringTools.startsWith(temp, "/*")) { + return true; + } + + return false; + } + + private static function isEndOfComment(input:String):Bool { + var temp:String = StringTools.rtrim(input); + if (StringTools.endsWith(temp, "*/")) { + return true; + } + + return false; + } + + private function addSemiColon(input:String):String { + //var idx:Int = input.indexOf("//"); + if (input.length == 0 || StringTools.trim(input) == "") return input; + var temp:String = input; + //var orig:String = input; + + //if (idx >= 0) { + //temp = temp.substr(0, idx - 1); + temp = StringTools.rtrim(temp); + if (!StringTools.endsWith(temp, "}") && + !StringTools.endsWith(temp, "{") && + !StringTools.endsWith(temp, ";") && + !StringTools.endsWith(temp, "*/")) { + temp += ";"; + } + //} + + return temp; + } + + private function removePublicFromClass(input:String):String { + var classPattern = ~/public\s+class/; + if (classPattern.match(input)) { + return StringTools.replace(input, "public ", ""); + } + + return input; + } + private function convertForLoop(input:String):String { var temp:String = input; var forPattern = ~/for\s*\(var\s+(\w+):\w+\s*=\s*(\d+);\1[<>=]+(\w+)\s*;\s*\1\S+\)\s*/; var forReplacePattern = ~/var\s+(\w+):\w+\s*=\s*(\d+);\1[<>=]+(\w+)\s*;\s*\1[^\)]*/; if (forPattern.match(input)) { var variable:String = forPattern.matched(1); var min:String = forPattern.matched(2); var max:String = forPattern.matched(3); var newFor:String = variable + " in " + min + "..." + max; temp = forReplacePattern.replace(temp, newFor); } return temp; } private function convertConstructorName(input:String):String { var constPattern = ~/function\s+(\w+)\(\S*\)/; if (constPattern.match(input)) { var t:String = constPattern.matched(1); for (stype in AllTypes.getInstance().getAllOrigNames(false)) { if (t == stype) { // if this function name matches a custom type name return StringTools.replace(input, t, "new"); } } } return input; } private function removeImports(input:String):String { var importPattern = ~/import\s+\S+/; if (importPattern.match(input)) { return ""; } return input; } private function convertClassName(input:String):String { var classPattern = ~/public\s+class\s+(\w+)/; var temp:String = input; if (classPattern.match(input)) { var className:String = classPattern.matched(1); var newName:String = className.charAt(0).toUpperCase() + className.substr(1); temp = StringTools.replace(temp, className, newName); } return temp; } private function convertInterfaceName(input:String):String { var classPattern = ~/public\s+interface\s+(\w+)/; var temp:String = input; if (classPattern.match(input)) { var className:String = classPattern.matched(1); var newName:String = className.charAt(0).toUpperCase() + className.substr(1); temp = StringTools.replace(temp, className, newName); } return temp; } private function convertPackage(input:String):String { var temp:String = input; if (input.indexOf(_hf.filePackage) >= 0) { var idx:Int = input.indexOf(" {"); if (idx >= 0) { temp = StringTools.replace(temp, " {", ";"); _foundPackage = true; } } return temp; } private function convertConstToVar(input:String):String { var temp:String = input; var constPattern = ~/\s+const\s+\S+/; if (constPattern.match(input)) { temp = StringTools.replace(temp, "const", "var"); } return temp; } private function convertTypes(input:String):String { var temp:String = input; var patterns:Array<EReg> = [ ~/var\s+\w+\s*:\s*(\w+)[;\s]*/, // var definition pattern ~/new\s+(\w+)\(\S*\)/, // object init pattern ~/:(\w+)/, // function def pattern ~/function\s+\S+\(\S*\):(\S*)/, // function return pattern ~/\W*(\w+)./]; // static function call pattern for (pattern in patterns) { if (pattern.match(input)) { var typeToConvert:String = pattern.matched(1); - //Lib.println(_hf.fullPath + ":" + _currentLine + ":" + typeToConvert); var objType:ObjectType = AllTypes.getInstance().getTypeByOrigName(typeToConvert, true); if (objType != null) { var newType:String = objType.normalizedName; temp = StringTools.replace(input, typeToConvert, newType); } } } return temp; } - private static function checkForTypes(input:String, hf:HaxeFile):Void { - /*var stype:String = checkForMatch(input); - - if (stype != null) { - addImport(CustomTypes.getInstance().getFullTypeByName(stype), hf); - } - - stype = checkForMatchFlash(input); - - if (stype != null) { - addImport(FlashAPI.getInstance().getFullTypeByName(stype), hf); + private static function checkForTypes(lineNum:Int, hf:HaxeFile):Void { + for (lineNums in _commentLines) { + if (lineNums == lineNum) { + return; + } } - */ + var input:String = hf.lines[lineNum]; for (stype in AllTypes.getInstance().getAllOrigNames(false)) { //Lib.println("checking for: " + stype); if (input.indexOf(stype) >= 0) { addImport(AllTypes.getInstance().getTypeByOrigName(stype, false).getFullNormalizedName(), hf); } } } private static function addImport(imp:String, hf:HaxeFile):Void { - Lib.println("adding import: " + imp); + //Lib.println("adding import: " + imp); for (i in hf.imports) { if (i == imp) { return; } } hf.imports.add(imp); } } \ No newline at end of file
JasonMiesionczek/As3toHaxe
cafa85acac3c448f2c475e9c74a2e8171fc11b05
re-designed type detection and refactoring
diff --git a/bin/As3toHaxe.n b/bin/As3toHaxe.n index b979646..1d0aaee 100644 Binary files a/bin/As3toHaxe.n and b/bin/As3toHaxe.n differ diff --git a/src/net/interaxia/as3tohaxe/Main.hx b/src/net/interaxia/as3tohaxe/Main.hx index cf81a28..7cb9d22 100644 --- a/src/net/interaxia/as3tohaxe/Main.hx +++ b/src/net/interaxia/as3tohaxe/Main.hx @@ -1,118 +1,121 @@ package net.interaxia.as3tohaxe; import neko.FileSystem; import neko.io.File; import neko.io.FileOutput; import neko.io.Path; import neko.Lib; import neko.Sys; +import net.interaxia.as3tohaxe.api.AllTypes; import net.interaxia.as3tohaxe.api.CustomTypes; import net.interaxia.as3tohaxe.api.FlashAPI; import net.interaxia.as3tohaxe.inspector.FileInspector; import net.interaxia.as3tohaxe.translator.Translator; /** * ... * @author Jason Miesionczek */ class Main { static function main() { var inputPath:String = ""; var outputPath:String = ""; if (Sys.args().length == 0) { inputPath = Sys.getCwd(); } else if (Sys.args().length == 2) { inputPath = Sys.args()[0]; outputPath = Sys.args()[1]; } try { if (!FileSystem.exists(outputPath)) { FileSystem.createDirectory(outputPath); } } catch (msg:String) { Lib.println("There was an error creating the specified output directory. Ensure the parent drive/directory exists and you have write permissions to it."); return; } Lib.println("Input path: " + inputPath); Lib.println("Output path: " + outputPath); Lib.println("Scanning input folder..."); var cpscanner:ClassPathScanner = new ClassPathScanner(inputPath); cpscanner.scan(); var haxeFiles:List<HaxeFile> = new List<HaxeFile>(); + AllTypes.getInstance().initAllTypes(); + Lib.println("Inspecting files..."); for (f in cpscanner.filesToParse) { var fi:FileInspector = new FileInspector(f); var hf:HaxeFile = fi.inspect(); haxeFiles.add(hf); } Lib.println("Collecting type information..."); - CustomTypes.getInstance().setupMatches(); + //CustomTypes.getInstance().setupMatches(); - Translator.initTypeRegs(); + //Translator.initTypeRegs(); for (f in haxeFiles) { Translator.compileTypes(f); } Lib.println("Translating files..."); for (f in haxeFiles) { var t:Translator = new Translator(f); t.translate(); } Lib.println("Generating output files..."); generateOutputFiles(haxeFiles, outputPath); Lib.println(haxeFiles.length + " files converted."); } static function generateOutputFiles(files:List < HaxeFile > , output:String) { for (file in files) { var fileName:String = Path.withoutDirectory(Path.withoutExtension(file.fullPath)); if (CustomTypes.getInstance().matches.exists(fileName)) { - var newfileName:String = CustomTypes.getInstance().matches.get(fileName); + var newfileName:String = AllTypes.getInstance().getTypeByOrigName(fileName, false).normalizedName;//CustomTypes.getInstance().matches.get(fileName); file.fullPath = StringTools.replace(file.fullPath, fileName, newfileName); } var fileOutputPath:String = output; if (file.filePackage.indexOf(".") >= 0) { var packageParts:Array < String > = file.filePackage.split("."); fileOutputPath = fileOutputPath + "/" + packageParts.join("/"); createOutputDirs(packageParts, output); } fileOutputPath += "/" + StringTools.replace(Path.withoutDirectory(file.fullPath), ".as", ".hx"); var fout:FileOutput = File.write(fileOutputPath, false); for (line in file.lines) { fout.writeString(line+"\n"); } fout.close(); } } static function createOutputDirs(parts:Array < String > , outputPath:String):Void { var currentPath:String = outputPath; for (p in parts) { currentPath += "/" + p; if (!FileSystem.exists(currentPath)) { FileSystem.createDirectory(currentPath); } } } } \ No newline at end of file diff --git a/src/net/interaxia/as3tohaxe/api/CustomTypes.hx b/src/net/interaxia/as3tohaxe/api/CustomTypes.hx index 6f282e5..bd4ae5b 100644 --- a/src/net/interaxia/as3tohaxe/api/CustomTypes.hx +++ b/src/net/interaxia/as3tohaxe/api/CustomTypes.hx @@ -1,78 +1,79 @@ /** * ... * @author Jason Miesionczek */ package net.interaxia.as3tohaxe.api; class CustomTypes { private static var _instance:CustomTypes; public static function getInstance():CustomTypes { if (_instance == null) { _instance = new CustomTypes(); } return _instance; } public var types(default, default): List<String>; public var matches(default, null): Hash<String>; private function new() { types = new List<String>(); matches = new Hash<String>(); matches.set("int", "Int"); matches.set("void", "Void"); matches.set("Number", "Float"); matches.set("Array", "Array<Dynamic>"); + matches.set("Boolean", "Bool"); } public function setupMatches():Void { for (stype in getShortNames()) { matches.set(stype, stype.charAt(0).toUpperCase() + stype.substr(1)); } } public function getTypeNormalized(originalName:String):String { for (t in types) { if (t == originalName) { var idx:Int = t.lastIndexOf("."); if (idx >= 0) { var type:String = t.substr(idx + 1); var orig:String = type; type = type.charAt(0).toUpperCase() + type.substr(1); return StringTools.replace(t, orig, type); } } } return originalName; } public function getFullTypeByName(name:String):String { for (t in types) { if (StringTools.endsWith(t, name)) { return getTypeNormalized(t); } } return name; } public function getShortNames():List < String > { var snames:List<String> = new List<String>(); for (t in types) { var idx:Int = t.lastIndexOf("."); if (idx >= 0) { snames.add(t.substr(idx+1)); } else { snames.add(t); } } return snames; } } \ No newline at end of file diff --git a/src/net/interaxia/as3tohaxe/api/FlashAPI.hx b/src/net/interaxia/as3tohaxe/api/FlashAPI.hx index 78f9d3e..dcc782e 100644 --- a/src/net/interaxia/as3tohaxe/api/FlashAPI.hx +++ b/src/net/interaxia/as3tohaxe/api/FlashAPI.hx @@ -1,57 +1,64 @@ /** * ... * @author Jason Miesionczek */ package net.interaxia.as3tohaxe.api; import neko.io.File; import neko.Lib; class FlashAPI { private static var _instance:FlashAPI; private var _types:List<String>; private var _shortTypes:List<String>; + public var objTypes(default, null):List<ObjectType>; public static function getInstance():FlashAPI { if (_instance == null) { _instance = new FlashAPI(); } return _instance; } public var types(getShortTypes, null):List<String>; private function getShortTypes():List < String > { return _shortTypes; } private function new() { _types = new List<String>(); _shortTypes = new List<String>(); + objTypes = new List<ObjectType>(); var inputXml:String = File.getContent("FlashAPI.xml"); var x : Xml = Xml.parse(inputXml).firstElement(); for (p in x.elements()) { var pname:String = p.get("name"); for (e in p.elements()) { var ename:String = e.firstChild().nodeValue; _shortTypes.add(ename); _types.add(pname + "." + ename); + var objType:ObjectType = new ObjectType(); + objType.typePackage = pname; + objType.originalName = ename; + objType.normalizedName = ename; + objTypes.add(objType); } } } public function getFullTypeByName(name:String):String { for (t in _types) { if (StringTools.endsWith(t, name)) { return t; } } return ""; } } \ No newline at end of file diff --git a/src/net/interaxia/as3tohaxe/inspector/FileInspector.hx b/src/net/interaxia/as3tohaxe/inspector/FileInspector.hx index fb27115..e8247d0 100644 --- a/src/net/interaxia/as3tohaxe/inspector/FileInspector.hx +++ b/src/net/interaxia/as3tohaxe/inspector/FileInspector.hx @@ -1,88 +1,97 @@ /** * ... * @author Jason Miesionczek */ package net.interaxia.as3tohaxe.inspector; import neko.io.FileInput; import neko.io.File; import haxe.io.Eof; import neko.Lib; +import net.interaxia.as3tohaxe.api.AllTypes; import net.interaxia.as3tohaxe.api.CustomTypes; +import net.interaxia.as3tohaxe.api.ObjectType; import net.interaxia.as3tohaxe.HaxeFile; class FileInspector { private var _inputFile:String; private var _fileObject:FileInput; private var _lines:List<String>; private var _package:String; private var _types:List<String>; private var _hf:HaxeFile; public function new(file:String) { _inputFile = file; _lines = new List<String>(); _types = new List<String>(); } public function inspect():HaxeFile { _hf = new HaxeFile(); _hf.fullPath = _inputFile; _fileObject = File.read(_inputFile, false); try { while (true) { if (_fileObject.eof()) break; var l:String = _fileObject.readLine(); _lines.add(l); _hf.lines.push(l); } } catch (ex:Eof) {} _fileObject.close(); detectPackage(); detectClasses(); detectInterfaces(); return _hf; } private function detectPackage():Void { var packagePattern = ~/package\s+([a-z.]+)/; for (line in _lines) { if (packagePattern.match(line)) { _package = packagePattern.matched(1); _hf.filePackage = _package; return; } } _package = ""; } private function detectClasses():Void { var classPattern = ~/public\s+class\s+(\w+)/; for (line in _lines) { if (classPattern.match(line)) { - var fullType:String = _package + "." + classPattern.matched(1); - CustomTypes.getInstance().types.add(fullType); - //Lib.println(fullType); + var objType:ObjectType = new ObjectType(); + objType.typePackage = _package; + objType.originalName = classPattern.matched(1); + objType.normalizeName(); + AllTypes.getInstance().types.add(objType); + } } } private function detectInterfaces():Void { var interfacePattern = ~/public\s+interface\s+(\w+)/; for (line in _lines) { if (interfacePattern.match(line)) { - var fullType:String = _package + "." + interfacePattern.matched(1); - CustomTypes.getInstance().types.add(fullType); - Lib.println("Interface found: " + fullType); + + var objType:ObjectType = new ObjectType(); + objType.typePackage = _package; + objType.originalName = interfacePattern.matched(1); + objType.normalizeName(); + AllTypes.getInstance().types.add(objType); + } } } } \ No newline at end of file diff --git a/src/net/interaxia/as3tohaxe/translator/Translator.hx b/src/net/interaxia/as3tohaxe/translator/Translator.hx index dd3bba5..30bdc4f 100644 --- a/src/net/interaxia/as3tohaxe/translator/Translator.hx +++ b/src/net/interaxia/as3tohaxe/translator/Translator.hx @@ -1,289 +1,253 @@ /** * ... * @author Jason Miesionczek */ package net.interaxia.as3tohaxe.translator; import neko.io.FileInput; import neko.io.File; import haxe.io.Eof; import neko.Lib; import net.interaxia.as3tohaxe.api.CustomTypes; import net.interaxia.as3tohaxe.api.FlashAPI; +import net.interaxia.as3tohaxe.api.ObjectType; import net.interaxia.as3tohaxe.HaxeFile; +import net.interaxia.as3tohaxe.api.AllTypes; class Translator { private var _fileObject:FileInput; private var _lines:Array<String>; private var _output:List<String>; private var _hf:HaxeFile; private var _foundPackage:Bool; + private var _currentLine:Int; private static var _typeRegs:List<EReg>; private static var _typeRegsFlash:List<EReg>; public function new(inputFile:HaxeFile) { _lines = new Array<String>(); _output = new List<String>(); _hf = inputFile; for (l in inputFile.lines) { _lines.push(l); } } public static function compileTypes(f:HaxeFile):Void { for (line in f.lines) { checkForTypes(line, f); // this will build the new list of imports } } public function translate():Void { //Lib.println("Translating "+_hf.fullPath+"..."); _foundPackage = false; var packagePos:Int = -1; var newLines:Array<String> = new Array<String>(); for (line in 0..._lines.length) { + _currentLine = line; var tempLine:String = _lines[line]; if (!_foundPackage) { tempLine = convertPackage(tempLine); } if (_foundPackage && packagePos < 0) { packagePos = line; } tempLine = removeImports(tempLine); tempLine = convertClassName(tempLine); tempLine = convertInterfaceName(tempLine); + tempLine = convertConstToVar(tempLine); tempLine = convertTypes(tempLine); tempLine = convertConstructorName(tempLine); tempLine = convertForLoop(tempLine); //_lines[line] = tempLine; newLines.push(tempLine); } var tempLines:Array<String> = newLines; tempLines.reverse(); for (line in 0...tempLines.length) { var temp:String = StringTools.ltrim(tempLines[line]); if (StringTools.startsWith(temp, "}")) { tempLines = tempLines.slice(line+1); break; } } tempLines.reverse(); newLines = tempLines; // insert the new import statements just below the package definition. for (imp in _hf.imports) { var impStr:String = " import " + imp + ";"; newLines.insert(packagePos + 1, impStr); } _hf.lines = newLines; } private function convertForLoop(input:String):String { var temp:String = input; var forPattern = ~/for\s*\(var\s+(\w+):\w+\s*=\s*(\d+);\1[<>=]+(\w+)\s*;\s*\1\S+\)\s*/; var forReplacePattern = ~/var\s+(\w+):\w+\s*=\s*(\d+);\1[<>=]+(\w+)\s*;\s*\1[^\)]*/; if (forPattern.match(input)) { var variable:String = forPattern.matched(1); var min:String = forPattern.matched(2); var max:String = forPattern.matched(3); var newFor:String = variable + " in " + min + "..." + max; temp = forReplacePattern.replace(temp, newFor); } return temp; } private function convertConstructorName(input:String):String { - var constPattern = ~/function\s+(\w+)\(\.*\)[^:]/; + var constPattern = ~/function\s+(\w+)\(\S*\)/; if (constPattern.match(input)) { var t:String = constPattern.matched(1); - for (stype in CustomTypes.getInstance().getShortNames()) { + for (stype in AllTypes.getInstance().getAllOrigNames(false)) { if (t == stype) { // if this function name matches a custom type name return StringTools.replace(input, t, "new"); } } } return input; } private function removeImports(input:String):String { var importPattern = ~/import\s+\S+/; if (importPattern.match(input)) { return ""; } return input; } private function convertClassName(input:String):String { var classPattern = ~/public\s+class\s+(\w+)/; var temp:String = input; if (classPattern.match(input)) { var className:String = classPattern.matched(1); var newName:String = className.charAt(0).toUpperCase() + className.substr(1); temp = StringTools.replace(temp, className, newName); } return temp; } private function convertInterfaceName(input:String):String { var classPattern = ~/public\s+interface\s+(\w+)/; var temp:String = input; if (classPattern.match(input)) { var className:String = classPattern.matched(1); var newName:String = className.charAt(0).toUpperCase() + className.substr(1); temp = StringTools.replace(temp, className, newName); } return temp; } private function convertPackage(input:String):String { var temp:String = input; if (input.indexOf(_hf.filePackage) >= 0) { var idx:Int = input.indexOf(" {"); if (idx >= 0) { temp = StringTools.replace(temp, " {", ";"); _foundPackage = true; } } return temp; } - private function convertTypes(input:String):String { + private function convertConstToVar(input:String):String { var temp:String = input; - var typeDefPattern = ~/var\s+\w+\s*:\s*(\w+)[;\s]*/; - var typeNewPattern = ~/new\s+(\w+)\(\S*\)/; - var funcParamPattern = ~/function\s+\w+\s*\(\w+:(\w+)\)/; - - if (typeDefPattern.match(input)) { - var typeToConvert:String = typeDefPattern.matched(1); - var newType:String = CustomTypes.getInstance().matches.get(typeToConvert); - if (newType != null) { - //Lib.println(typeToConvert + " => " + newType); - temp = StringTools.replace(input, typeToConvert, newType); - } - } + var constPattern = ~/\s+const\s+\S+/; - if (typeNewPattern.match(input)) { - var typeToConvert:String = typeNewPattern.matched(1); - var newType:String = CustomTypes.getInstance().matches.get(typeToConvert); - if (newType != null) { - //Lib.println(typeToConvert + " => " + newType); - temp = StringTools.replace(input, typeToConvert, newType);//typeNewPattern.replace(temp, newType); - } - } - - if (funcParamPattern.match(input)) { - var typeToConvert:String = funcParamPattern.matched(1); - var newType:String = CustomTypes.getInstance().matches.get(typeToConvert); - if (newType != null) { - temp = StringTools.replace(input, typeToConvert, newType); - } + if (constPattern.match(input)) { + temp = StringTools.replace(temp, "const", "var"); } return temp; } - public static function initTypeRegs():Void { - _typeRegs = new List<EReg>(); - _typeRegsFlash = new List<EReg>(); - for (stype in CustomTypes.getInstance().getShortNames()) { - var reg:EReg = new EReg(":\\s*(" + stype + ")", ""); - _typeRegs.add(reg); - //var reg:EReg = new EReg("public\\s+class\\s+(" + stype + ")", ""); - //_typeRegs.add(reg); - var reg:EReg = new EReg("\\s+implements\\s+(" + stype + ")", ""); - _typeRegs.add(reg); - reg = new EReg("\\s+extends\\s+(" + stype + ")", ""); - _typeRegs.add(reg); - } + private function convertTypes(input:String):String { + var temp:String = input; - for (stype in FlashAPI.getInstance().types) { - var reg:EReg = new EReg(":\\s*(" + stype + ")", ""); - _typeRegsFlash.add(reg); - } - } - - private static function checkForMatch(input:String):String { - for (reg in _typeRegs) { - if (reg.match(input)) { - return reg.matched(1); - } - } - return null; - } - - private static function checkForMatchFlash(input:String):String { - for (reg in _typeRegsFlash) { - if (reg.match(input)) { - return reg.matched(1); + var patterns:Array<EReg> = [ ~/var\s+\w+\s*:\s*(\w+)[;\s]*/, // var definition pattern + ~/new\s+(\w+)\(\S*\)/, // object init pattern + ~/:(\w+)/, // function def pattern + ~/function\s+\S+\(\S*\):(\S*)/, // function return pattern + ~/\W*(\w+)./]; // static function call pattern + + for (pattern in patterns) { + if (pattern.match(input)) { + var typeToConvert:String = pattern.matched(1); + //Lib.println(_hf.fullPath + ":" + _currentLine + ":" + typeToConvert); + var objType:ObjectType = AllTypes.getInstance().getTypeByOrigName(typeToConvert, true); + if (objType != null) { + var newType:String = objType.normalizedName; + temp = StringTools.replace(input, typeToConvert, newType); + } + + } } - return null; + return temp; } + private static function checkForTypes(input:String, hf:HaxeFile):Void { - var stype:String = checkForMatch(input); + /*var stype:String = checkForMatch(input); if (stype != null) { - //Lib.println(stype); - var out:String = addImport(CustomTypes.getInstance().getFullTypeByName(stype), hf); - //Lib.println(out); - //CustomTypes.getInstance().matches.set(stype, out.substr(out.lastIndexOf(".")+1)); + addImport(CustomTypes.getInstance().getFullTypeByName(stype), hf); } stype = checkForMatchFlash(input); if (stype != null) { addImport(FlashAPI.getInstance().getFullTypeByName(stype), hf); } - + */ + for (stype in AllTypes.getInstance().getAllOrigNames(false)) { + //Lib.println("checking for: " + stype); + if (input.indexOf(stype) >= 0) { + addImport(AllTypes.getInstance().getTypeByOrigName(stype, false).getFullNormalizedName(), hf); + } + } } - private static function addImport(imp:String, hf:HaxeFile):String { - var found:Bool = false; - var out:String = ""; + private static function addImport(imp:String, hf:HaxeFile):Void { + Lib.println("adding import: " + imp); for (i in hf.imports) { if (i == imp) { - found = true; - out = i; - break; + return; } } - if (!found) { - hf.imports.add(imp); - out = imp; - //Lib.println(" import " + imp); - } - - return out; + hf.imports.add(imp); + } } \ No newline at end of file
JasonMiesionczek/As3toHaxe
30c480a1ab7921fbf0ad6fdf650c75e46c42c484
translator now correctly detects interfaces and refactors type names found inside function parameter definitions
diff --git a/bin/As3toHaxe.n b/bin/As3toHaxe.n index d4746ce..b979646 100644 Binary files a/bin/As3toHaxe.n and b/bin/As3toHaxe.n differ diff --git a/src/net/interaxia/as3tohaxe/inspector/FileInspector.hx b/src/net/interaxia/as3tohaxe/inspector/FileInspector.hx index 3a87e7e..fb27115 100644 --- a/src/net/interaxia/as3tohaxe/inspector/FileInspector.hx +++ b/src/net/interaxia/as3tohaxe/inspector/FileInspector.hx @@ -1,76 +1,88 @@ /** * ... * @author Jason Miesionczek */ package net.interaxia.as3tohaxe.inspector; import neko.io.FileInput; import neko.io.File; import haxe.io.Eof; import neko.Lib; import net.interaxia.as3tohaxe.api.CustomTypes; import net.interaxia.as3tohaxe.HaxeFile; class FileInspector { private var _inputFile:String; private var _fileObject:FileInput; private var _lines:List<String>; private var _package:String; private var _types:List<String>; private var _hf:HaxeFile; public function new(file:String) { _inputFile = file; _lines = new List<String>(); _types = new List<String>(); } public function inspect():HaxeFile { _hf = new HaxeFile(); _hf.fullPath = _inputFile; _fileObject = File.read(_inputFile, false); try { while (true) { if (_fileObject.eof()) break; var l:String = _fileObject.readLine(); _lines.add(l); _hf.lines.push(l); } } catch (ex:Eof) {} _fileObject.close(); detectPackage(); detectClasses(); + detectInterfaces(); return _hf; } private function detectPackage():Void { var packagePattern = ~/package\s+([a-z.]+)/; for (line in _lines) { if (packagePattern.match(line)) { _package = packagePattern.matched(1); _hf.filePackage = _package; return; } } _package = ""; } private function detectClasses():Void { var classPattern = ~/public\s+class\s+(\w+)/; for (line in _lines) { if (classPattern.match(line)) { var fullType:String = _package + "." + classPattern.matched(1); CustomTypes.getInstance().types.add(fullType); //Lib.println(fullType); } } } + private function detectInterfaces():Void { + var interfacePattern = ~/public\s+interface\s+(\w+)/; + for (line in _lines) { + if (interfacePattern.match(line)) { + var fullType:String = _package + "." + interfacePattern.matched(1); + CustomTypes.getInstance().types.add(fullType); + Lib.println("Interface found: " + fullType); + } + } + } + } \ No newline at end of file diff --git a/src/net/interaxia/as3tohaxe/translator/Translator.hx b/src/net/interaxia/as3tohaxe/translator/Translator.hx index 905845a..dd3bba5 100644 --- a/src/net/interaxia/as3tohaxe/translator/Translator.hx +++ b/src/net/interaxia/as3tohaxe/translator/Translator.hx @@ -1,263 +1,289 @@ /** * ... * @author Jason Miesionczek */ package net.interaxia.as3tohaxe.translator; import neko.io.FileInput; import neko.io.File; import haxe.io.Eof; import neko.Lib; import net.interaxia.as3tohaxe.api.CustomTypes; import net.interaxia.as3tohaxe.api.FlashAPI; import net.interaxia.as3tohaxe.HaxeFile; class Translator { private var _fileObject:FileInput; private var _lines:Array<String>; private var _output:List<String>; private var _hf:HaxeFile; private var _foundPackage:Bool; private static var _typeRegs:List<EReg>; private static var _typeRegsFlash:List<EReg>; public function new(inputFile:HaxeFile) { _lines = new Array<String>(); _output = new List<String>(); _hf = inputFile; for (l in inputFile.lines) { _lines.push(l); } } public static function compileTypes(f:HaxeFile):Void { for (line in f.lines) { checkForTypes(line, f); // this will build the new list of imports } } public function translate():Void { //Lib.println("Translating "+_hf.fullPath+"..."); _foundPackage = false; var packagePos:Int = -1; var newLines:Array<String> = new Array<String>(); for (line in 0..._lines.length) { var tempLine:String = _lines[line]; if (!_foundPackage) { tempLine = convertPackage(tempLine); } if (_foundPackage && packagePos < 0) { packagePos = line; } tempLine = removeImports(tempLine); tempLine = convertClassName(tempLine); + tempLine = convertInterfaceName(tempLine); tempLine = convertTypes(tempLine); tempLine = convertConstructorName(tempLine); tempLine = convertForLoop(tempLine); //_lines[line] = tempLine; newLines.push(tempLine); } var tempLines:Array<String> = newLines; tempLines.reverse(); for (line in 0...tempLines.length) { var temp:String = StringTools.ltrim(tempLines[line]); if (StringTools.startsWith(temp, "}")) { tempLines = tempLines.slice(line+1); break; } } tempLines.reverse(); newLines = tempLines; // insert the new import statements just below the package definition. for (imp in _hf.imports) { var impStr:String = " import " + imp + ";"; newLines.insert(packagePos + 1, impStr); } _hf.lines = newLines; } private function convertForLoop(input:String):String { var temp:String = input; var forPattern = ~/for\s*\(var\s+(\w+):\w+\s*=\s*(\d+);\1[<>=]+(\w+)\s*;\s*\1\S+\)\s*/; var forReplacePattern = ~/var\s+(\w+):\w+\s*=\s*(\d+);\1[<>=]+(\w+)\s*;\s*\1[^\)]*/; if (forPattern.match(input)) { var variable:String = forPattern.matched(1); var min:String = forPattern.matched(2); var max:String = forPattern.matched(3); var newFor:String = variable + " in " + min + "..." + max; temp = forReplacePattern.replace(temp, newFor); } return temp; } private function convertConstructorName(input:String):String { var constPattern = ~/function\s+(\w+)\(\.*\)[^:]/; if (constPattern.match(input)) { var t:String = constPattern.matched(1); for (stype in CustomTypes.getInstance().getShortNames()) { if (t == stype) { // if this function name matches a custom type name return StringTools.replace(input, t, "new"); } } } return input; } private function removeImports(input:String):String { var importPattern = ~/import\s+\S+/; if (importPattern.match(input)) { return ""; } return input; } private function convertClassName(input:String):String { var classPattern = ~/public\s+class\s+(\w+)/; var temp:String = input; if (classPattern.match(input)) { var className:String = classPattern.matched(1); var newName:String = className.charAt(0).toUpperCase() + className.substr(1); temp = StringTools.replace(temp, className, newName); } return temp; } + private function convertInterfaceName(input:String):String { + var classPattern = ~/public\s+interface\s+(\w+)/; + var temp:String = input; + if (classPattern.match(input)) { + var className:String = classPattern.matched(1); + var newName:String = className.charAt(0).toUpperCase() + className.substr(1); + temp = StringTools.replace(temp, className, newName); + } + + return temp; + } + private function convertPackage(input:String):String { var temp:String = input; if (input.indexOf(_hf.filePackage) >= 0) { var idx:Int = input.indexOf(" {"); if (idx >= 0) { temp = StringTools.replace(temp, " {", ";"); _foundPackage = true; } } return temp; } private function convertTypes(input:String):String { var temp:String = input; var typeDefPattern = ~/var\s+\w+\s*:\s*(\w+)[;\s]*/; var typeNewPattern = ~/new\s+(\w+)\(\S*\)/; + var funcParamPattern = ~/function\s+\w+\s*\(\w+:(\w+)\)/; if (typeDefPattern.match(input)) { var typeToConvert:String = typeDefPattern.matched(1); var newType:String = CustomTypes.getInstance().matches.get(typeToConvert); if (newType != null) { //Lib.println(typeToConvert + " => " + newType); temp = StringTools.replace(input, typeToConvert, newType); } } if (typeNewPattern.match(input)) { var typeToConvert:String = typeNewPattern.matched(1); var newType:String = CustomTypes.getInstance().matches.get(typeToConvert); if (newType != null) { //Lib.println(typeToConvert + " => " + newType); temp = StringTools.replace(input, typeToConvert, newType);//typeNewPattern.replace(temp, newType); } } + if (funcParamPattern.match(input)) { + var typeToConvert:String = funcParamPattern.matched(1); + var newType:String = CustomTypes.getInstance().matches.get(typeToConvert); + if (newType != null) { + temp = StringTools.replace(input, typeToConvert, newType); + } + } + return temp; } public static function initTypeRegs():Void { _typeRegs = new List<EReg>(); _typeRegsFlash = new List<EReg>(); for (stype in CustomTypes.getInstance().getShortNames()) { var reg:EReg = new EReg(":\\s*(" + stype + ")", ""); _typeRegs.add(reg); //var reg:EReg = new EReg("public\\s+class\\s+(" + stype + ")", ""); //_typeRegs.add(reg); + var reg:EReg = new EReg("\\s+implements\\s+(" + stype + ")", ""); + _typeRegs.add(reg); + reg = new EReg("\\s+extends\\s+(" + stype + ")", ""); + _typeRegs.add(reg); } for (stype in FlashAPI.getInstance().types) { var reg:EReg = new EReg(":\\s*(" + stype + ")", ""); _typeRegsFlash.add(reg); } } private static function checkForMatch(input:String):String { for (reg in _typeRegs) { if (reg.match(input)) { return reg.matched(1); } } return null; } private static function checkForMatchFlash(input:String):String { for (reg in _typeRegsFlash) { if (reg.match(input)) { return reg.matched(1); } } return null; } private static function checkForTypes(input:String, hf:HaxeFile):Void { var stype:String = checkForMatch(input); if (stype != null) { //Lib.println(stype); var out:String = addImport(CustomTypes.getInstance().getFullTypeByName(stype), hf); //Lib.println(out); //CustomTypes.getInstance().matches.set(stype, out.substr(out.lastIndexOf(".")+1)); } stype = checkForMatchFlash(input); if (stype != null) { addImport(FlashAPI.getInstance().getFullTypeByName(stype), hf); } } private static function addImport(imp:String, hf:HaxeFile):String { var found:Bool = false; var out:String = ""; for (i in hf.imports) { if (i == imp) { found = true; out = i; break; } } if (!found) { hf.imports.add(imp); out = imp; //Lib.println(" import " + imp); } return out; } } \ No newline at end of file
JasonMiesionczek/As3toHaxe
97ef44a3cfe053f17725f2724322b248019f7362
added code to remove last curly brace that remained from the package block
diff --git a/bin/As3toHaxe.n b/bin/As3toHaxe.n index c10e41a..d4746ce 100644 Binary files a/bin/As3toHaxe.n and b/bin/As3toHaxe.n differ diff --git a/src/net/interaxia/as3tohaxe/Main.hx b/src/net/interaxia/as3tohaxe/Main.hx index 6d3533d..cf81a28 100644 --- a/src/net/interaxia/as3tohaxe/Main.hx +++ b/src/net/interaxia/as3tohaxe/Main.hx @@ -1,116 +1,118 @@ package net.interaxia.as3tohaxe; import neko.FileSystem; import neko.io.File; import neko.io.FileOutput; import neko.io.Path; import neko.Lib; import neko.Sys; import net.interaxia.as3tohaxe.api.CustomTypes; import net.interaxia.as3tohaxe.api.FlashAPI; import net.interaxia.as3tohaxe.inspector.FileInspector; import net.interaxia.as3tohaxe.translator.Translator; /** * ... * @author Jason Miesionczek */ class Main { static function main() { var inputPath:String = ""; var outputPath:String = ""; + if (Sys.args().length == 0) { + inputPath = Sys.getCwd(); + + } else if (Sys.args().length == 2) { + inputPath = Sys.args()[0]; + outputPath = Sys.args()[1]; + } + try { if (!FileSystem.exists(outputPath)) { FileSystem.createDirectory(outputPath); } } catch (msg:String) { Lib.println("There was an error creating the specified output directory. Ensure the parent drive/directory exists and you have write permissions to it."); return; } - if (Sys.args().length == 0) { - inputPath = Sys.getCwd(); - - } else if (Sys.args().length == 2) { - inputPath = Sys.args()[0]; - outputPath = Sys.args()[1]; - } + Lib.println("Input path: " + inputPath); Lib.println("Output path: " + outputPath); Lib.println("Scanning input folder..."); var cpscanner:ClassPathScanner = new ClassPathScanner(inputPath); cpscanner.scan(); var haxeFiles:List<HaxeFile> = new List<HaxeFile>(); Lib.println("Inspecting files..."); for (f in cpscanner.filesToParse) { var fi:FileInspector = new FileInspector(f); var hf:HaxeFile = fi.inspect(); haxeFiles.add(hf); } Lib.println("Collecting type information..."); CustomTypes.getInstance().setupMatches(); Translator.initTypeRegs(); for (f in haxeFiles) { Translator.compileTypes(f); } Lib.println("Translating files..."); for (f in haxeFiles) { var t:Translator = new Translator(f); t.translate(); } Lib.println("Generating output files..."); generateOutputFiles(haxeFiles, outputPath); Lib.println(haxeFiles.length + " files converted."); } static function generateOutputFiles(files:List < HaxeFile > , output:String) { for (file in files) { var fileName:String = Path.withoutDirectory(Path.withoutExtension(file.fullPath)); if (CustomTypes.getInstance().matches.exists(fileName)) { var newfileName:String = CustomTypes.getInstance().matches.get(fileName); file.fullPath = StringTools.replace(file.fullPath, fileName, newfileName); } var fileOutputPath:String = output; if (file.filePackage.indexOf(".") >= 0) { var packageParts:Array < String > = file.filePackage.split("."); fileOutputPath = fileOutputPath + "/" + packageParts.join("/"); createOutputDirs(packageParts, output); } fileOutputPath += "/" + StringTools.replace(Path.withoutDirectory(file.fullPath), ".as", ".hx"); var fout:FileOutput = File.write(fileOutputPath, false); for (line in file.lines) { fout.writeString(line+"\n"); } fout.close(); } } static function createOutputDirs(parts:Array < String > , outputPath:String):Void { var currentPath:String = outputPath; for (p in parts) { currentPath += "/" + p; if (!FileSystem.exists(currentPath)) { FileSystem.createDirectory(currentPath); } } } } \ No newline at end of file diff --git a/src/net/interaxia/as3tohaxe/translator/Translator.hx b/src/net/interaxia/as3tohaxe/translator/Translator.hx index f585f19..905845a 100644 --- a/src/net/interaxia/as3tohaxe/translator/Translator.hx +++ b/src/net/interaxia/as3tohaxe/translator/Translator.hx @@ -1,250 +1,263 @@ /** * ... * @author Jason Miesionczek */ package net.interaxia.as3tohaxe.translator; import neko.io.FileInput; import neko.io.File; import haxe.io.Eof; import neko.Lib; import net.interaxia.as3tohaxe.api.CustomTypes; import net.interaxia.as3tohaxe.api.FlashAPI; import net.interaxia.as3tohaxe.HaxeFile; class Translator { private var _fileObject:FileInput; private var _lines:Array<String>; private var _output:List<String>; private var _hf:HaxeFile; private var _foundPackage:Bool; private static var _typeRegs:List<EReg>; private static var _typeRegsFlash:List<EReg>; public function new(inputFile:HaxeFile) { _lines = new Array<String>(); _output = new List<String>(); _hf = inputFile; for (l in inputFile.lines) { _lines.push(l); } } public static function compileTypes(f:HaxeFile):Void { for (line in f.lines) { checkForTypes(line, f); // this will build the new list of imports } } public function translate():Void { //Lib.println("Translating "+_hf.fullPath+"..."); _foundPackage = false; var packagePos:Int = -1; var newLines:Array<String> = new Array<String>(); for (line in 0..._lines.length) { var tempLine:String = _lines[line]; if (!_foundPackage) { tempLine = convertPackage(tempLine); } if (_foundPackage && packagePos < 0) { packagePos = line; } tempLine = removeImports(tempLine); tempLine = convertClassName(tempLine); tempLine = convertTypes(tempLine); tempLine = convertConstructorName(tempLine); tempLine = convertForLoop(tempLine); //_lines[line] = tempLine; newLines.push(tempLine); } + var tempLines:Array<String> = newLines; + tempLines.reverse(); + for (line in 0...tempLines.length) { + var temp:String = StringTools.ltrim(tempLines[line]); + if (StringTools.startsWith(temp, "}")) { + tempLines = tempLines.slice(line+1); + break; + } + + } + tempLines.reverse(); + newLines = tempLines; + // insert the new import statements just below the package definition. for (imp in _hf.imports) { var impStr:String = " import " + imp + ";"; newLines.insert(packagePos + 1, impStr); } _hf.lines = newLines; } private function convertForLoop(input:String):String { var temp:String = input; var forPattern = ~/for\s*\(var\s+(\w+):\w+\s*=\s*(\d+);\1[<>=]+(\w+)\s*;\s*\1\S+\)\s*/; var forReplacePattern = ~/var\s+(\w+):\w+\s*=\s*(\d+);\1[<>=]+(\w+)\s*;\s*\1[^\)]*/; if (forPattern.match(input)) { var variable:String = forPattern.matched(1); var min:String = forPattern.matched(2); var max:String = forPattern.matched(3); var newFor:String = variable + " in " + min + "..." + max; temp = forReplacePattern.replace(temp, newFor); } return temp; } private function convertConstructorName(input:String):String { var constPattern = ~/function\s+(\w+)\(\.*\)[^:]/; if (constPattern.match(input)) { var t:String = constPattern.matched(1); for (stype in CustomTypes.getInstance().getShortNames()) { if (t == stype) { // if this function name matches a custom type name return StringTools.replace(input, t, "new"); } } } return input; } private function removeImports(input:String):String { var importPattern = ~/import\s+\S+/; if (importPattern.match(input)) { return ""; } return input; } private function convertClassName(input:String):String { var classPattern = ~/public\s+class\s+(\w+)/; var temp:String = input; if (classPattern.match(input)) { var className:String = classPattern.matched(1); var newName:String = className.charAt(0).toUpperCase() + className.substr(1); temp = StringTools.replace(temp, className, newName); } return temp; } private function convertPackage(input:String):String { var temp:String = input; if (input.indexOf(_hf.filePackage) >= 0) { var idx:Int = input.indexOf(" {"); if (idx >= 0) { temp = StringTools.replace(temp, " {", ";"); _foundPackage = true; } } return temp; } private function convertTypes(input:String):String { var temp:String = input; var typeDefPattern = ~/var\s+\w+\s*:\s*(\w+)[;\s]*/; var typeNewPattern = ~/new\s+(\w+)\(\S*\)/; if (typeDefPattern.match(input)) { var typeToConvert:String = typeDefPattern.matched(1); var newType:String = CustomTypes.getInstance().matches.get(typeToConvert); if (newType != null) { //Lib.println(typeToConvert + " => " + newType); temp = StringTools.replace(input, typeToConvert, newType); } } if (typeNewPattern.match(input)) { var typeToConvert:String = typeNewPattern.matched(1); var newType:String = CustomTypes.getInstance().matches.get(typeToConvert); if (newType != null) { //Lib.println(typeToConvert + " => " + newType); temp = StringTools.replace(input, typeToConvert, newType);//typeNewPattern.replace(temp, newType); } } return temp; } public static function initTypeRegs():Void { _typeRegs = new List<EReg>(); _typeRegsFlash = new List<EReg>(); for (stype in CustomTypes.getInstance().getShortNames()) { var reg:EReg = new EReg(":\\s*(" + stype + ")", ""); _typeRegs.add(reg); //var reg:EReg = new EReg("public\\s+class\\s+(" + stype + ")", ""); //_typeRegs.add(reg); } for (stype in FlashAPI.getInstance().types) { var reg:EReg = new EReg(":\\s*(" + stype + ")", ""); _typeRegsFlash.add(reg); } } private static function checkForMatch(input:String):String { for (reg in _typeRegs) { if (reg.match(input)) { return reg.matched(1); } } return null; } private static function checkForMatchFlash(input:String):String { for (reg in _typeRegsFlash) { if (reg.match(input)) { return reg.matched(1); } } return null; } private static function checkForTypes(input:String, hf:HaxeFile):Void { var stype:String = checkForMatch(input); if (stype != null) { //Lib.println(stype); var out:String = addImport(CustomTypes.getInstance().getFullTypeByName(stype), hf); //Lib.println(out); //CustomTypes.getInstance().matches.set(stype, out.substr(out.lastIndexOf(".")+1)); } stype = checkForMatchFlash(input); if (stype != null) { addImport(FlashAPI.getInstance().getFullTypeByName(stype), hf); } } private static function addImport(imp:String, hf:HaxeFile):String { var found:Bool = false; var out:String = ""; for (i in hf.imports) { if (i == imp) { found = true; out = i; break; } } if (!found) { hf.imports.add(imp); out = imp; //Lib.println(" import " + imp); } return out; } } \ No newline at end of file
JasonMiesionczek/As3toHaxe
8c8f3d64345112fb8c70f40b6df81ae97b56467a
fixed command line args for directories. changed all directory separators to be uniform
diff --git a/bin/As3toHaxe.n b/bin/As3toHaxe.n index 00206c9..c10e41a 100644 Binary files a/bin/As3toHaxe.n and b/bin/As3toHaxe.n differ diff --git a/run.bat b/run.bat index 5e38944..c018153 100644 --- a/run.bat +++ b/run.bat @@ -1,4 +1,4 @@ @echo off cd bin -neko As3toHaxe.n +neko As3toHaxe.n d:/development/ffilmation d:/development/as3tohaxe_output pause diff --git a/src/net/interaxia/as3tohaxe/ClassPathScanner.hx b/src/net/interaxia/as3tohaxe/ClassPathScanner.hx index 36fb60c..03a2fd2 100644 --- a/src/net/interaxia/as3tohaxe/ClassPathScanner.hx +++ b/src/net/interaxia/as3tohaxe/ClassPathScanner.hx @@ -1,63 +1,63 @@ /** * ... * @author Jason Miesionczek */ package net.interaxia.as3tohaxe; import neko.FileSystem; import neko.io.File; import neko.io.Path; import neko.Lib; class ClassPathScanner { public var rootFiles(default, null) : Array<String>; public var filesToParse(default, null) : List<String>; private var _inputPath:String; private var _dirsToSearch:List<String>; private var _filesToParse:List<String>; public function new(path:String) { this._inputPath = path; this._dirsToSearch = new List<String>(); filesToParse = new List<String>(); } public function scan():Void { rootFiles = FileSystem.readDirectory(_inputPath); for (file in rootFiles) { - var fullPath:String = _inputPath + "\\" + file; + var fullPath:String = _inputPath + "/" + file; if (FileSystem.isDirectory(fullPath)) { _dirsToSearch.add(fullPath); } else { if (Path.extension(file) == "as") filesToParse.add(fullPath); } } for (dir in _dirsToSearch) scanDirectory(dir); } private function scanDirectory(dir:String):Void { var filesInDir:Array<String> = FileSystem.readDirectory(dir); for (file in filesInDir) { - var fullPath:String = dir + "\\" + file; + var fullPath:String = dir + "/" + file; if (FileSystem.isDirectory(fullPath)) { scanDirectory(fullPath); } var ext:String = Path.extension(file); if (ext.toLowerCase() == "as") { filesToParse.add(fullPath); } } } } \ No newline at end of file diff --git a/src/net/interaxia/as3tohaxe/Main.hx b/src/net/interaxia/as3tohaxe/Main.hx index 48feb5e..6d3533d 100644 --- a/src/net/interaxia/as3tohaxe/Main.hx +++ b/src/net/interaxia/as3tohaxe/Main.hx @@ -1,119 +1,116 @@ package net.interaxia.as3tohaxe; import neko.FileSystem; import neko.io.File; import neko.io.FileOutput; import neko.io.Path; import neko.Lib; import neko.Sys; import net.interaxia.as3tohaxe.api.CustomTypes; import net.interaxia.as3tohaxe.api.FlashAPI; import net.interaxia.as3tohaxe.inspector.FileInspector; import net.interaxia.as3tohaxe.translator.Translator; /** * ... * @author Jason Miesionczek */ class Main { static function main() { var inputPath:String = ""; - var outputPath:String = "d:\\development\\as3tohaxe_output"; + var outputPath:String = ""; - if (!FileSystem.exists(outputPath)) { - FileSystem.createDirectory(outputPath); + try { + if (!FileSystem.exists(outputPath)) { + FileSystem.createDirectory(outputPath); + } + } catch (msg:String) { + Lib.println("There was an error creating the specified output directory. Ensure the parent drive/directory exists and you have write permissions to it."); + return; } if (Sys.args().length == 0) { inputPath = Sys.getCwd(); - Lib.println(inputPath); + + } else if (Sys.args().length == 2) { + inputPath = Sys.args()[0]; + outputPath = Sys.args()[1]; } + Lib.println("Input path: " + inputPath); + Lib.println("Output path: " + outputPath); + Lib.println("Scanning input folder..."); - var cpscanner:ClassPathScanner = new ClassPathScanner("d:\\development\\ffilmation"); + var cpscanner:ClassPathScanner = new ClassPathScanner(inputPath); cpscanner.scan(); var haxeFiles:List<HaxeFile> = new List<HaxeFile>(); Lib.println("Inspecting files..."); for (f in cpscanner.filesToParse) { var fi:FileInspector = new FileInspector(f); var hf:HaxeFile = fi.inspect(); haxeFiles.add(hf); - - } Lib.println("Collecting type information..."); CustomTypes.getInstance().setupMatches(); Translator.initTypeRegs(); for (f in haxeFiles) { Translator.compileTypes(f); } - - + Lib.println("Translating files..."); for (f in haxeFiles) { var t:Translator = new Translator(f); t.translate(); } - - //for (t in CustomTypes.getInstance().matches.keys()) { - // Lib.println(t + " => " + CustomTypes.getInstance().matches.get(t)); - //} - + Lib.println("Generating output files..."); generateOutputFiles(haxeFiles, outputPath); Lib.println(haxeFiles.length + " files converted."); } static function generateOutputFiles(files:List < HaxeFile > , output:String) { for (file in files) { var fileName:String = Path.withoutDirectory(Path.withoutExtension(file.fullPath)); - //Lib.println(fileName); + if (CustomTypes.getInstance().matches.exists(fileName)) { var newfileName:String = CustomTypes.getInstance().matches.get(fileName); file.fullPath = StringTools.replace(file.fullPath, fileName, newfileName); } var fileOutputPath:String = output; if (file.filePackage.indexOf(".") >= 0) { var packageParts:Array < String > = file.filePackage.split("."); - fileOutputPath = fileOutputPath + "\\" + packageParts.join("\\"); + fileOutputPath = fileOutputPath + "/" + packageParts.join("/"); createOutputDirs(packageParts, output); } - - - - fileOutputPath += "\\" + StringTools.replace(Path.withoutDirectory(file.fullPath), ".as", ".hx"); + + fileOutputPath += "/" + StringTools.replace(Path.withoutDirectory(file.fullPath), ".as", ".hx"); var fout:FileOutput = File.write(fileOutputPath, false); for (line in file.lines) { fout.writeString(line+"\n"); } fout.close(); - - //Lib.println(fileOutputPath); - - - } } static function createOutputDirs(parts:Array < String > , outputPath:String):Void { var currentPath:String = outputPath; for (p in parts) { - currentPath += "\\" + p; + currentPath += "/" + p; if (!FileSystem.exists(currentPath)) { FileSystem.createDirectory(currentPath); } } } } \ No newline at end of file
JasonMiesionczek/As3toHaxe
8a5de2f5e5afc03e99745e48da9cfe1446f68f41
output is generating properly. more testing needed
diff --git a/bin/As3toHaxe.n b/bin/As3toHaxe.n index e350d8c..00206c9 100644 Binary files a/bin/As3toHaxe.n and b/bin/As3toHaxe.n differ diff --git a/src/net/interaxia/as3tohaxe/HaxeFile.hx b/src/net/interaxia/as3tohaxe/HaxeFile.hx index c13af1f..5b086e6 100644 --- a/src/net/interaxia/as3tohaxe/HaxeFile.hx +++ b/src/net/interaxia/as3tohaxe/HaxeFile.hx @@ -1,20 +1,20 @@ /** * ... * @author Jason Miesionczek */ package net.interaxia.as3tohaxe; class HaxeFile { public var filePackage(default, default):String; - public var lines(default, null):List<String>; + public var lines(default, default):Array<String>; public var fullPath(default, default):String; public var imports(default, null):List<String>; public function new() { - lines = new List<String>(); + lines = new Array<String>(); imports = new List<String>(); } } \ No newline at end of file diff --git a/src/net/interaxia/as3tohaxe/Main.hx b/src/net/interaxia/as3tohaxe/Main.hx index 6c29f2d..48feb5e 100644 --- a/src/net/interaxia/as3tohaxe/Main.hx +++ b/src/net/interaxia/as3tohaxe/Main.hx @@ -1,49 +1,119 @@ package net.interaxia.as3tohaxe; +import neko.FileSystem; +import neko.io.File; +import neko.io.FileOutput; import neko.io.Path; import neko.Lib; import neko.Sys; +import net.interaxia.as3tohaxe.api.CustomTypes; import net.interaxia.as3tohaxe.api.FlashAPI; import net.interaxia.as3tohaxe.inspector.FileInspector; import net.interaxia.as3tohaxe.translator.Translator; /** * ... * @author Jason Miesionczek */ class Main { static function main() { var inputPath:String = ""; + var outputPath:String = "d:\\development\\as3tohaxe_output"; + + if (!FileSystem.exists(outputPath)) { + FileSystem.createDirectory(outputPath); + } + if (Sys.args().length == 0) { inputPath = Sys.getCwd(); Lib.println(inputPath); } + Lib.println("Scanning input folder..."); var cpscanner:ClassPathScanner = new ClassPathScanner("d:\\development\\ffilmation"); cpscanner.scan(); var haxeFiles:List<HaxeFile> = new List<HaxeFile>(); + Lib.println("Inspecting files..."); for (f in cpscanner.filesToParse) { var fi:FileInspector = new FileInspector(f); var hf:HaxeFile = fi.inspect(); haxeFiles.add(hf); } + Lib.println("Collecting type information..."); + CustomTypes.getInstance().setupMatches(); + + Translator.initTypeRegs(); + for (f in haxeFiles) { Translator.compileTypes(f); } + + Lib.println("Translating files..."); for (f in haxeFiles) { var t:Translator = new Translator(f); t.translate(); } + + //for (t in CustomTypes.getInstance().matches.keys()) { + // Lib.println(t + " => " + CustomTypes.getInstance().matches.get(t)); + //} + + Lib.println("Generating output files..."); + generateOutputFiles(haxeFiles, outputPath); + Lib.println(haxeFiles.length + " files converted."); + } + + static function generateOutputFiles(files:List < HaxeFile > , output:String) { + + for (file in files) { + var fileName:String = Path.withoutDirectory(Path.withoutExtension(file.fullPath)); + //Lib.println(fileName); + if (CustomTypes.getInstance().matches.exists(fileName)) { + var newfileName:String = CustomTypes.getInstance().matches.get(fileName); + file.fullPath = StringTools.replace(file.fullPath, fileName, newfileName); + } + var fileOutputPath:String = output; + if (file.filePackage.indexOf(".") >= 0) { + var packageParts:Array < String > = file.filePackage.split("."); + fileOutputPath = fileOutputPath + "\\" + packageParts.join("\\"); + createOutputDirs(packageParts, output); + } + + + + fileOutputPath += "\\" + StringTools.replace(Path.withoutDirectory(file.fullPath), ".as", ".hx"); + + var fout:FileOutput = File.write(fileOutputPath, false); + for (line in file.lines) { + fout.writeString(line+"\n"); + } + fout.close(); + + //Lib.println(fileOutputPath); + + + + } + } + + static function createOutputDirs(parts:Array < String > , outputPath:String):Void { + var currentPath:String = outputPath; + for (p in parts) { + currentPath += "\\" + p; + if (!FileSystem.exists(currentPath)) { + FileSystem.createDirectory(currentPath); + } + } } } \ No newline at end of file diff --git a/src/net/interaxia/as3tohaxe/api/CustomTypes.hx b/src/net/interaxia/as3tohaxe/api/CustomTypes.hx index 8ad2659..6f282e5 100644 --- a/src/net/interaxia/as3tohaxe/api/CustomTypes.hx +++ b/src/net/interaxia/as3tohaxe/api/CustomTypes.hx @@ -1,72 +1,78 @@ /** * ... * @author Jason Miesionczek */ package net.interaxia.as3tohaxe.api; class CustomTypes { private static var _instance:CustomTypes; public static function getInstance():CustomTypes { if (_instance == null) { _instance = new CustomTypes(); } return _instance; } public var types(default, default): List<String>; public var matches(default, null): Hash<String>; private function new() { types = new List<String>(); matches = new Hash<String>(); matches.set("int", "Int"); matches.set("void", "Void"); matches.set("Number", "Float"); matches.set("Array", "Array<Dynamic>"); } + public function setupMatches():Void { + for (stype in getShortNames()) { + matches.set(stype, stype.charAt(0).toUpperCase() + stype.substr(1)); + } + } + public function getTypeNormalized(originalName:String):String { for (t in types) { if (t == originalName) { var idx:Int = t.lastIndexOf("."); if (idx >= 0) { var type:String = t.substr(idx + 1); var orig:String = type; type = type.charAt(0).toUpperCase() + type.substr(1); return StringTools.replace(t, orig, type); } } } return originalName; } public function getFullTypeByName(name:String):String { for (t in types) { if (StringTools.endsWith(t, name)) { return getTypeNormalized(t); } } return name; } public function getShortNames():List < String > { var snames:List<String> = new List<String>(); for (t in types) { var idx:Int = t.lastIndexOf("."); if (idx >= 0) { snames.add(t.substr(idx+1)); } else { snames.add(t); } } return snames; } } \ No newline at end of file diff --git a/src/net/interaxia/as3tohaxe/api/FlashAPI.hx b/src/net/interaxia/as3tohaxe/api/FlashAPI.hx index 2a802b9..78f9d3e 100644 --- a/src/net/interaxia/as3tohaxe/api/FlashAPI.hx +++ b/src/net/interaxia/as3tohaxe/api/FlashAPI.hx @@ -1,59 +1,57 @@ /** * ... * @author Jason Miesionczek */ package net.interaxia.as3tohaxe.api; import neko.io.File; import neko.Lib; class FlashAPI { private static var _instance:FlashAPI; private var _types:List<String>; private var _shortTypes:List<String>; public static function getInstance():FlashAPI { if (_instance == null) { _instance = new FlashAPI(); } return _instance; } public var types(getShortTypes, null):List<String>; private function getShortTypes():List < String > { return _shortTypes; } private function new() { _types = new List<String>(); _shortTypes = new List<String>(); var inputXml:String = File.getContent("FlashAPI.xml"); var x : Xml = Xml.parse(inputXml).firstElement(); for (p in x.elements()) { var pname:String = p.get("name"); - //Lib.println(pname); for (e in p.elements()) { var ename:String = e.firstChild().nodeValue; _shortTypes.add(ename); - //Lib.println(" " + ename); _types.add(pname + "." + ename); } } } public function getFullTypeByName(name:String):String { for (t in _types) { if (StringTools.endsWith(t, name)) { return t; } } return ""; } } \ No newline at end of file diff --git a/src/net/interaxia/as3tohaxe/inspector/FileInspector.hx b/src/net/interaxia/as3tohaxe/inspector/FileInspector.hx index 92e579b..3a87e7e 100644 --- a/src/net/interaxia/as3tohaxe/inspector/FileInspector.hx +++ b/src/net/interaxia/as3tohaxe/inspector/FileInspector.hx @@ -1,76 +1,76 @@ /** * ... * @author Jason Miesionczek */ package net.interaxia.as3tohaxe.inspector; import neko.io.FileInput; import neko.io.File; import haxe.io.Eof; import neko.Lib; import net.interaxia.as3tohaxe.api.CustomTypes; import net.interaxia.as3tohaxe.HaxeFile; class FileInspector { private var _inputFile:String; private var _fileObject:FileInput; private var _lines:List<String>; private var _package:String; private var _types:List<String>; private var _hf:HaxeFile; public function new(file:String) { _inputFile = file; _lines = new List<String>(); _types = new List<String>(); } public function inspect():HaxeFile { _hf = new HaxeFile(); _hf.fullPath = _inputFile; _fileObject = File.read(_inputFile, false); try { while (true) { if (_fileObject.eof()) break; var l:String = _fileObject.readLine(); _lines.add(l); - _hf.lines.add(l); + _hf.lines.push(l); } } catch (ex:Eof) {} _fileObject.close(); detectPackage(); detectClasses(); return _hf; } private function detectPackage():Void { var packagePattern = ~/package\s+([a-z.]+)/; for (line in _lines) { if (packagePattern.match(line)) { _package = packagePattern.matched(1); _hf.filePackage = _package; return; } } _package = ""; } private function detectClasses():Void { var classPattern = ~/public\s+class\s+(\w+)/; for (line in _lines) { if (classPattern.match(line)) { var fullType:String = _package + "." + classPattern.matched(1); CustomTypes.getInstance().types.add(fullType); //Lib.println(fullType); } } } } \ No newline at end of file diff --git a/src/net/interaxia/as3tohaxe/translator/Translator.hx b/src/net/interaxia/as3tohaxe/translator/Translator.hx index 7d3b596..f585f19 100644 --- a/src/net/interaxia/as3tohaxe/translator/Translator.hx +++ b/src/net/interaxia/as3tohaxe/translator/Translator.hx @@ -1,154 +1,250 @@ /** * ... * @author Jason Miesionczek */ package net.interaxia.as3tohaxe.translator; import neko.io.FileInput; import neko.io.File; import haxe.io.Eof; import neko.Lib; import net.interaxia.as3tohaxe.api.CustomTypes; import net.interaxia.as3tohaxe.api.FlashAPI; import net.interaxia.as3tohaxe.HaxeFile; class Translator { private var _fileObject:FileInput; - private var _lines:List<String>; + private var _lines:Array<String>; private var _output:List<String>; private var _hf:HaxeFile; private var _foundPackage:Bool; + private static var _typeRegs:List<EReg>; + private static var _typeRegsFlash:List<EReg>; + public function new(inputFile:HaxeFile) { - _lines = new List<String>(); + _lines = new Array<String>(); _output = new List<String>(); _hf = inputFile; - - - - + for (l in inputFile.lines) { - _lines.add(l); + _lines.push(l); } } public static function compileTypes(f:HaxeFile):Void { for (line in f.lines) { checkForTypes(line, f); // this will build the new list of imports } } public function translate():Void { - Lib.println(_hf.fullPath); + //Lib.println("Translating "+_hf.fullPath+"..."); _foundPackage = false; + var packagePos:Int = -1; + var newLines:Array<String> = new Array<String>(); - for (line in _lines) { - var tempLine:String = line; + for (line in 0..._lines.length) { + var tempLine:String = _lines[line]; if (!_foundPackage) { tempLine = convertPackage(tempLine); } + + if (_foundPackage && packagePos < 0) { + packagePos = line; + } + tempLine = removeImports(tempLine); tempLine = convertClassName(tempLine); tempLine = convertTypes(tempLine); + tempLine = convertConstructorName(tempLine); + tempLine = convertForLoop(tempLine); + + //_lines[line] = tempLine; + newLines.push(tempLine); + } + + // insert the new import statements just below the package definition. + for (imp in _hf.imports) { + var impStr:String = " import " + imp + ";"; + newLines.insert(packagePos + 1, impStr); + } + + _hf.lines = newLines; + + + + } + + private function convertForLoop(input:String):String { + var temp:String = input; + var forPattern = ~/for\s*\(var\s+(\w+):\w+\s*=\s*(\d+);\1[<>=]+(\w+)\s*;\s*\1\S+\)\s*/; + var forReplacePattern = ~/var\s+(\w+):\w+\s*=\s*(\d+);\1[<>=]+(\w+)\s*;\s*\1[^\)]*/; + + if (forPattern.match(input)) { + var variable:String = forPattern.matched(1); + var min:String = forPattern.matched(2); + var max:String = forPattern.matched(3); - Lib.println(tempLine); + var newFor:String = variable + " in " + min + "..." + max; + temp = forReplacePattern.replace(temp, newFor); + } + + return temp; + + } + + private function convertConstructorName(input:String):String { + var constPattern = ~/function\s+(\w+)\(\.*\)[^:]/; + if (constPattern.match(input)) { + var t:String = constPattern.matched(1); + for (stype in CustomTypes.getInstance().getShortNames()) { + if (t == stype) { // if this function name matches a custom type name + return StringTools.replace(input, t, "new"); + } + } } + return input; } private function removeImports(input:String):String { + var importPattern = ~/import\s+\S+/; + if (importPattern.match(input)) { + return ""; + } + return input; } private function convertClassName(input:String):String { var classPattern = ~/public\s+class\s+(\w+)/; var temp:String = input; if (classPattern.match(input)) { var className:String = classPattern.matched(1); var newName:String = className.charAt(0).toUpperCase() + className.substr(1); temp = StringTools.replace(temp, className, newName); } return temp; } private function convertPackage(input:String):String { var temp:String = input; if (input.indexOf(_hf.filePackage) >= 0) { var idx:Int = input.indexOf(" {"); if (idx >= 0) { temp = StringTools.replace(temp, " {", ";"); _foundPackage = true; } } return temp; } private function convertTypes(input:String):String { var temp:String = input; var typeDefPattern = ~/var\s+\w+\s*:\s*(\w+)[;\s]*/; var typeNewPattern = ~/new\s+(\w+)\(\S*\)/; if (typeDefPattern.match(input)) { var typeToConvert:String = typeDefPattern.matched(1); var newType:String = CustomTypes.getInstance().matches.get(typeToConvert); if (newType != null) { - Lib.println(typeToConvert + " => " + newType); + //Lib.println(typeToConvert + " => " + newType); temp = StringTools.replace(input, typeToConvert, newType); } } if (typeNewPattern.match(input)) { var typeToConvert:String = typeNewPattern.matched(1); var newType:String = CustomTypes.getInstance().matches.get(typeToConvert); if (newType != null) { - Lib.println(typeToConvert + " => " + newType); + //Lib.println(typeToConvert + " => " + newType); temp = StringTools.replace(input, typeToConvert, newType);//typeNewPattern.replace(temp, newType); } } return temp; } - private static function checkForTypes(input:String, hf:HaxeFile):Void { + public static function initTypeRegs():Void { + _typeRegs = new List<EReg>(); + _typeRegsFlash = new List<EReg>(); for (stype in CustomTypes.getInstance().getShortNames()) { - if (input.indexOf(stype) >= 0) { - var out:String = addImport(CustomTypes.getInstance().getFullTypeByName(stype), hf); - CustomTypes.getInstance().matches.set(stype, out.substr(out.lastIndexOf(".")+1)); - } + var reg:EReg = new EReg(":\\s*(" + stype + ")", ""); + _typeRegs.add(reg); + //var reg:EReg = new EReg("public\\s+class\\s+(" + stype + ")", ""); + //_typeRegs.add(reg); } for (stype in FlashAPI.getInstance().types) { - if (input.indexOf(stype) >= 0) { - addImport(FlashAPI.getInstance().getFullTypeByName(stype), hf); + var reg:EReg = new EReg(":\\s*(" + stype + ")", ""); + _typeRegsFlash.add(reg); + } + } + + private static function checkForMatch(input:String):String { + for (reg in _typeRegs) { + if (reg.match(input)) { + return reg.matched(1); } } + + return null; + } + + private static function checkForMatchFlash(input:String):String { + for (reg in _typeRegsFlash) { + if (reg.match(input)) { + return reg.matched(1); + } + } + + return null; + } + + private static function checkForTypes(input:String, hf:HaxeFile):Void { + var stype:String = checkForMatch(input); + + if (stype != null) { + //Lib.println(stype); + var out:String = addImport(CustomTypes.getInstance().getFullTypeByName(stype), hf); + //Lib.println(out); + //CustomTypes.getInstance().matches.set(stype, out.substr(out.lastIndexOf(".")+1)); + } + + stype = checkForMatchFlash(input); + + if (stype != null) { + addImport(FlashAPI.getInstance().getFullTypeByName(stype), hf); + } + } private static function addImport(imp:String, hf:HaxeFile):String { var found:Bool = false; var out:String = ""; for (i in hf.imports) { if (i == imp) { found = true; out = i; break; } } if (!found) { hf.imports.add(imp); out = imp; - Lib.println(" import " + hf.imports.last()); + //Lib.println(" import " + imp); } return out; } } \ No newline at end of file
JasonMiesionczek/As3toHaxe
2c45db0683c22324f634dbe7434002b30a5cb843
Initial check-in
diff --git a/As3toHaxe.hxproj b/As3toHaxe.hxproj new file mode 100644 index 0000000..8e1544d --- /dev/null +++ b/As3toHaxe.hxproj @@ -0,0 +1,49 @@ +<?xml version="1.0" encoding="utf-8"?> +<project> + <!-- Output SWF options --> + <output> + <movie disabled="False" /> + <movie input="" /> + <movie path="bin\As3toHaxe.n" /> + <movie fps="0" /> + <movie width="0" /> + <movie height="0" /> + <movie version="12" /> + <movie background="#FFFFFF" /> + </output> + <!-- Other classes to be compiled into your SWF --> + <classpaths> + <class path="src" /> + </classpaths> + <!-- Build options --> + <build> + <option directives="" /> + <option flashStrict="False" /> + <option mainClass="net.interaxia.as3tohaxe.Main" /> + <option override="False" /> + <option verbose="False" /> + <option additional="" /> + </build> + <!-- haxelib libraries --> + <haxelib> + <!-- example: <library name="..." /> --> + </haxelib> + <!-- Class files to compile (other referenced classes will automatically be included) --> + <compileTargets> + <compile path="src\net\interaxia\as3tohaxe\Main.hx" /> + </compileTargets> + <!-- Paths to exclude from the Project Explorer tree --> + <hiddenPaths> + <!-- example: <hidden path="..." /> --> + </hiddenPaths> + <!-- Executed before build --> + <preBuildCommand /> + <!-- Executed after build --> + <postBuildCommand alwaysRun="False" /> + <!-- Other project options --> + <options> + <option showHiddenPaths="False" /> + <option testMovie="Custom" /> + <option testMovieCommand="run.bat" /> + </options> +</project> \ No newline at end of file diff --git a/bin/As3toHaxe.n b/bin/As3toHaxe.n new file mode 100644 index 0000000..e350d8c Binary files /dev/null and b/bin/As3toHaxe.n differ diff --git a/bin/FlashAPI.xml b/bin/FlashAPI.xml new file mode 100644 index 0000000..7f5adac --- /dev/null +++ b/bin/FlashAPI.xml @@ -0,0 +1,298 @@ +<?xml version="1.0" encoding="utf-8" ?> +<packages> + <package name="flash"> + <type>Boot</type> + <type>Error</type> + <type>Lib</type> + <type>Memory</type> + <type>Vector</type> + </package> + <package name="flash.accessibility"> + <type>Accessibility</type> + <type>AccessibilityImplementation</type> + <type>AccessibilityProperties</type> + </package> + <package name="flash.diplay"> + <type>AVM1Movie</type> + <type>ActionScriptVersion</type> + <type>Bitmap</type> + <type>BitmapData</type> + <type>BitmapDataChannel</type> + <type>BlendMode</type> + <type>CapsStyle</type> + <type>DisplayObject</type> + <type>DisplayObjectContainer</type> + <type>FrameLabel</type> + <type>GradientType</type> + <type>Graphics</type> + <type>GraphicsBitmapFill</type> + <type>GraphicsEndFill</type> + <type>GraphicsGradientFill</type> + <type>GraphicsPath</type> + <type>GraphicsPathCommand</type> + <type>GraphicsPathWinding</type> + <type>GraphicsSolidFill</type> + <type>GraphicsStroke</type> + <type>GraphicsTrianglePath</type> + <type>IBitmapDrawable</type> + <type>IGraphicsData</type> + <type>IGraphicsFill</type> + <type>IGraphicsPath</type> + <type>IGraphicsStroke</type> + <type>InteractiveObject</type> + <type>InterpolationMethod</type> + <type>JointStyle</type> + <type>LineScaleMode</type> + <type>Loader</type> + <type>LoaderInfo</type> + <type>MorphShape</type> + <type>MovieClip</type> + <type>PixelSnapping</type> + <type>SWFVersion</type> + <type>Scene</type> + <type>Shader</type> + <type>ShaderData</type> + <type>ShaderInput</type> + <type>ShaderJob</type> + <type>ShaderParameter</type> + <type>ShaderParameterType</type> + <type>ShaderPrecision</type> + <type>Shape</type> + <type>SimpleButton</type> + <type>SpreadMethod</type> + <type>Sprite</type> + <type>Stage</type> + <type>StageAlign</type> + <type>StageDisplayState</type> + <type>StageQuality</type> + <type>StageScaleMode</type> + <type>TriangleCulling</type> + </package> + <package name="flash.errors"> + <type>EOFError</type> + <type>IOError</type> + <type>IllegalOperationError</type> + <type>InvalidSWFError</type> + <type>MemoryError</type> + <type>ScriptTimeoutError</type> + <type>StackOverflowError</type> + </package> + <package name="flash.events"> + <type>ActivityEvent</type> + <type>AsyncErrorEvent</type> + <type>ContextMenuEvent</type> + <type>DataEvent</type> + <type>ErrorEvent</type> + <type>Event</type> + <type>EventDispatcher</type> + <type>EventPhase</type> + <type>FocusEvent</type> + <type>FullScreenEvent</type> + <type>HTTPStatusEvent</type> + <type>IEventDspatcher</type> + <type>IMEEvent</type> + <type>IOErrorEvent</type> + <type>KeyboardEvent</type> + <type>MouseEvent</type> + <type>NetFilterEvent</type> + <type>NetStatusEvent</type> + <type>ProgressEvent</type> + <type>SampleDataEvent</type> + <type>SecurityErrorEvent</type> + <type>ShaderEvent</type> + <type>StatusEvent</type> + <type>SyncEvent</type> + <type>TextEvent</type> + <type>TimerEvent</type> + <type>WeakFunctionClosure</type> + <type>WeakMethodClosure</type> + </package> + <package name="flash.external"> + <type>ExternalInterface</type> + </package> + <package name="flash.filters"> + <type>BevelFilter</type> + <type>BitmapFilter</type> + <type>BitmapFilterQuality</type> + <type>BitmapFilterType</type> + <type>BlurFilter</type> + <type>ColorMatrixFilter</type> + <type>ConvolutionFilter</type> + <type>DisplacementMapFilter</type> + <type>DropShadowFilter</type> + <type>GlowFilter</type> + <type>GradientBevelFilter</type> + <type>GradientGlowFilter</type> + <type>ShaderFilter</type> + </package> + <package name="flash.geom"> + <type>ColorTransform</type> + <type>Matrix</type> + <type>Matrix3D</type> + <type>Orientation3D</type> + <type>PerspectiveProjection</type> + <type>Point</type> + <type>Rectangle</type> + <type>Transform</type> + <type>Utils3D</type> + <type>Vector3D</type> + </package> + <package name="flash.media"> + <type>Camera</type> + <type>ID3Info</type> + <type>Microphone</type> + <type>Sound</type> + <type>SoundChannel</type> + <type>SoundCodec</type> + <type>SoundLoaderContext</type> + <type>SoundMixer</type> + <type>SoundTransform</type> + <type>Video</type> + </package> + <package name="flash.net"> + <type>DynamicPropertyOutput</type> + <type>FileFilter</type> + <type>FileReference</type> + <type>FileReferenceList</type> + <type>IDynamicPropertyOutput</type> + <type>IDynamicPropertyWriter</type> + <type>LocalConnection</type> + <type>NetConnection</type> + <type>NetStream</type> + <type>NetStreamInfo</type> + <type>NetStreamPlayOptions</type> + <type>NetStreamPlayTransitions</type> + <type>ObjectEncoding</type> + <type>Responder</type> + <type>SharedObject</type> + <type>SharedObjectFlushStatus</type> + <type>Socket</type> + <type>URLLoader</type> + <type>URLLoaderDataFormat</type> + <type>URLRequest</type> + <type>URLRequestHeader</type> + <type>URLRequestMethod</type> + <type>URLStream</type> + <type>URLVariables</type> + <type>XMLSocket</type> + </package> + <package name="flash.printing"> + <type>PrintJob</type> + <type>PrintJobOptions</type> + <type>PrintJobOrientation</type> + </package> + <package name="flash.sampler"> + <type>Api</type> + <type>DeleteObjectSample</type> + <type>NewObjectSample</type> + <type>Sample</type> + <type>StackFrame</type> + </package> + <package name="flash.system"> + <type>ApplicationDomain</type> + <type>Capabilities</type> + <type>FSCommand</type> + <type>IME</type> + <type>IMEConversionMode</type> + <type>JPEGLoaderContext</type> + <type>LoaderContext</type> + <type>Security</type> + <type>SecurityDomain</type> + <type>SecurityPanel</type> + <type>System</type> + </package> + <package name="flash.text.engine"> + <type>BreakOpportunity</type> + <type>CFFHinting</type> + <type>ContentElement</type> + <type>DigitCase</type> + <type>DigitWidth</type> + <type>EastAsianJustifier</type> + <type>ElementFormat</type> + <type>FontDescription</type> + <type>FontLookup</type> + <type>FontMetrics</type> + <type>FontPosture</type> + <type>FontWeight</type> + <type>GraphicElement</type> + <type>GroupElement</type> + <type>JustificationStyle</type> + <type>Kerning</type> + <type>LigatureLevel</type> + <type>LineJustification</type> + <type>RenderingMode</type> + <type>SpaceJustifier</type> + <type>TabAlignment</type> + <type>TabStop</type> + <type>TextBaseline</type> + <type>TextBlock</type> + <type>TextElement</type> + <type>TextJustifier</type> + <type>TextLine</type> + <type>TextLineCreationResult</type> + <type>TextLineMirrorRegion</type> + <type>TextLineValidity</type> + <type>TextRotation</type> + <type>TypographicCase</type> + </package> + <package name="flash.text"> + <type>AntiAliasType</type> + <type>CSMSettings</type> + <type>Font</type> + <type>FontStyle</type> + <type>FontType</type> + <type>GridFitType</type> + <type>StaticText</type> + <type>TextColorType</type> + <type>TextDisplayMode</type> + <type>TextExtent</type> + <type>TextField</type> + <type>TextFieldAutoSize</type> + <type>TextFieldType</type> + <type>TextFormat</type> + <type>TextFormatAlign</type> + <type>TextFormatDisplay</type> + <type>TextLineMetrics</type> + <type>TextRenderer</type> + <type>TextRun</type> + <type>TextSnapshot</type> + </package> + <package name="flash.trace"> + <type>Trace</type> + </package> + <package name="flash.ui"> + <type>ContextMenu</type> + <type>ContextMenuBuiltInItems</type> + <type>ContextMenuClipboardItems</type> + <type>ContextMenuItem</type> + <type>KeyLocation</type> + <type>Keyboard</type> + <type>Mouse</type> + <type>MouseCursor</type> + </package> + <package name="flash.utils"> + <type>ByteArray</type> + <type>Dictionary</type> + <type>Endian</type> + <type>IDataInput</type> + <type>IDataOutput</type> + <type>IExternalizable</type> + <type>Namespace</type> + <type>ObjectInput</type> + <type>ObjectOutput</type> + <type>Proxy</type> + <type>QName</type> + <type>SetIntervalTimer</type> + <type>Timer</type> + <type>TypedDictionary</type> + </package> + <package name="flash.xml"> + <type>XML</type> + <type>XMLDocument</type> + <type>XMLList</type> + <type>XMLNode</type> + <type>XMLNodeType</type> + <type>XMLParser</type> + <type>XMLTag</type> + </package> +</packages> \ No newline at end of file diff --git a/run.bat b/run.bat new file mode 100644 index 0000000..5e38944 --- /dev/null +++ b/run.bat @@ -0,0 +1,4 @@ +@echo off +cd bin +neko As3toHaxe.n +pause diff --git a/src/net/interaxia/as3tohaxe/ClassPathScanner.hx b/src/net/interaxia/as3tohaxe/ClassPathScanner.hx new file mode 100644 index 0000000..36fb60c --- /dev/null +++ b/src/net/interaxia/as3tohaxe/ClassPathScanner.hx @@ -0,0 +1,63 @@ +/** + * ... + * @author Jason Miesionczek + */ + +package net.interaxia.as3tohaxe; +import neko.FileSystem; +import neko.io.File; +import neko.io.Path; +import neko.Lib; + +class ClassPathScanner { + + public var rootFiles(default, null) : Array<String>; + public var filesToParse(default, null) : List<String>; + + private var _inputPath:String; + private var _dirsToSearch:List<String>; + private var _filesToParse:List<String>; + + public function new(path:String) { + this._inputPath = path; + this._dirsToSearch = new List<String>(); + filesToParse = new List<String>(); + } + + public function scan():Void { + rootFiles = FileSystem.readDirectory(_inputPath); + + for (file in rootFiles) { + var fullPath:String = _inputPath + "\\" + file; + if (FileSystem.isDirectory(fullPath)) { + _dirsToSearch.add(fullPath); + } else { + if (Path.extension(file) == "as") + filesToParse.add(fullPath); + } + } + + for (dir in _dirsToSearch) + scanDirectory(dir); + } + + private function scanDirectory(dir:String):Void { + var filesInDir:Array<String> = FileSystem.readDirectory(dir); + for (file in filesInDir) { + var fullPath:String = dir + "\\" + file; + if (FileSystem.isDirectory(fullPath)) { + scanDirectory(fullPath); + } + + var ext:String = Path.extension(file); + if (ext.toLowerCase() == "as") { + filesToParse.add(fullPath); + } + } + + + } + + + +} \ No newline at end of file diff --git a/src/net/interaxia/as3tohaxe/HaxeFile.hx b/src/net/interaxia/as3tohaxe/HaxeFile.hx new file mode 100644 index 0000000..c13af1f --- /dev/null +++ b/src/net/interaxia/as3tohaxe/HaxeFile.hx @@ -0,0 +1,20 @@ +/** + * ... + * @author Jason Miesionczek + */ + +package net.interaxia.as3tohaxe; + +class HaxeFile { + + public var filePackage(default, default):String; + public var lines(default, null):List<String>; + public var fullPath(default, default):String; + public var imports(default, null):List<String>; + + public function new() { + lines = new List<String>(); + imports = new List<String>(); + } + +} \ No newline at end of file diff --git a/src/net/interaxia/as3tohaxe/Main.hx b/src/net/interaxia/as3tohaxe/Main.hx new file mode 100644 index 0000000..6c29f2d --- /dev/null +++ b/src/net/interaxia/as3tohaxe/Main.hx @@ -0,0 +1,49 @@ +package net.interaxia.as3tohaxe; + +import neko.io.Path; +import neko.Lib; +import neko.Sys; +import net.interaxia.as3tohaxe.api.FlashAPI; +import net.interaxia.as3tohaxe.inspector.FileInspector; +import net.interaxia.as3tohaxe.translator.Translator; + +/** + * ... + * @author Jason Miesionczek + */ + +class Main { + + static function main() { + var inputPath:String = ""; + if (Sys.args().length == 0) { + inputPath = Sys.getCwd(); + Lib.println(inputPath); + } + + var cpscanner:ClassPathScanner = new ClassPathScanner("d:\\development\\ffilmation"); + cpscanner.scan(); + + var haxeFiles:List<HaxeFile> = new List<HaxeFile>(); + + for (f in cpscanner.filesToParse) { + + var fi:FileInspector = new FileInspector(f); + var hf:HaxeFile = fi.inspect(); + + haxeFiles.add(hf); + + + } + + for (f in haxeFiles) { + Translator.compileTypes(f); + } + + for (f in haxeFiles) { + var t:Translator = new Translator(f); + t.translate(); + } + } + +} \ No newline at end of file diff --git a/src/net/interaxia/as3tohaxe/api/CustomTypes.hx b/src/net/interaxia/as3tohaxe/api/CustomTypes.hx new file mode 100644 index 0000000..8ad2659 --- /dev/null +++ b/src/net/interaxia/as3tohaxe/api/CustomTypes.hx @@ -0,0 +1,72 @@ +/** + * ... + * @author Jason Miesionczek + */ + +package net.interaxia.as3tohaxe.api; + +class CustomTypes { + + private static var _instance:CustomTypes; + public static function getInstance():CustomTypes { + if (_instance == null) { + _instance = new CustomTypes(); + } + + return _instance; + } + + public var types(default, default): List<String>; + public var matches(default, null): Hash<String>; + + private function new() { + types = new List<String>(); + matches = new Hash<String>(); + + matches.set("int", "Int"); + matches.set("void", "Void"); + matches.set("Number", "Float"); + matches.set("Array", "Array<Dynamic>"); + } + + public function getTypeNormalized(originalName:String):String { + for (t in types) { + if (t == originalName) { + var idx:Int = t.lastIndexOf("."); + if (idx >= 0) { + var type:String = t.substr(idx + 1); + var orig:String = type; + type = type.charAt(0).toUpperCase() + type.substr(1); + return StringTools.replace(t, orig, type); + } + } + } + + return originalName; + } + + public function getFullTypeByName(name:String):String { + for (t in types) { + if (StringTools.endsWith(t, name)) { + return getTypeNormalized(t); + } + } + + return name; + } + + public function getShortNames():List < String > { + var snames:List<String> = new List<String>(); + for (t in types) { + var idx:Int = t.lastIndexOf("."); + if (idx >= 0) { + snames.add(t.substr(idx+1)); + } else { + snames.add(t); + } + } + + return snames; + } + +} \ No newline at end of file diff --git a/src/net/interaxia/as3tohaxe/api/FlashAPI.hx b/src/net/interaxia/as3tohaxe/api/FlashAPI.hx new file mode 100644 index 0000000..2a802b9 --- /dev/null +++ b/src/net/interaxia/as3tohaxe/api/FlashAPI.hx @@ -0,0 +1,59 @@ +/** + * ... + * @author Jason Miesionczek + */ + +package net.interaxia.as3tohaxe.api; +import neko.io.File; +import neko.Lib; + +class FlashAPI { + + private static var _instance:FlashAPI; + private var _types:List<String>; + private var _shortTypes:List<String>; + + public static function getInstance():FlashAPI { + if (_instance == null) { + _instance = new FlashAPI(); + } + + return _instance; + } + + public var types(getShortTypes, null):List<String>; + + private function getShortTypes():List < String > { + return _shortTypes; + } + + private function new() { + _types = new List<String>(); + _shortTypes = new List<String>(); + var inputXml:String = File.getContent("FlashAPI.xml"); + var x : Xml = Xml.parse(inputXml).firstElement(); + for (p in x.elements()) { + var pname:String = p.get("name"); + //Lib.println(pname); + for (e in p.elements()) { + var ename:String = e.firstChild().nodeValue; + _shortTypes.add(ename); + //Lib.println(" " + ename); + _types.add(pname + "." + ename); + } + } + + } + + public function getFullTypeByName(name:String):String { + for (t in _types) { + if (StringTools.endsWith(t, name)) { + return t; + } + + } + + return ""; + } + +} \ No newline at end of file diff --git a/src/net/interaxia/as3tohaxe/inspector/FileInspector.hx b/src/net/interaxia/as3tohaxe/inspector/FileInspector.hx new file mode 100644 index 0000000..92e579b --- /dev/null +++ b/src/net/interaxia/as3tohaxe/inspector/FileInspector.hx @@ -0,0 +1,76 @@ +/** + * ... + * @author Jason Miesionczek + */ + +package net.interaxia.as3tohaxe.inspector; +import neko.io.FileInput; +import neko.io.File; +import haxe.io.Eof; +import neko.Lib; +import net.interaxia.as3tohaxe.api.CustomTypes; +import net.interaxia.as3tohaxe.HaxeFile; + +class FileInspector { + + private var _inputFile:String; + private var _fileObject:FileInput; + private var _lines:List<String>; + private var _package:String; + private var _types:List<String>; + private var _hf:HaxeFile; + + public function new(file:String) { + _inputFile = file; + _lines = new List<String>(); + _types = new List<String>(); + } + + public function inspect():HaxeFile { + _hf = new HaxeFile(); + _hf.fullPath = _inputFile; + _fileObject = File.read(_inputFile, false); + try { + while (true) { + if (_fileObject.eof()) break; + var l:String = _fileObject.readLine(); + _lines.add(l); + _hf.lines.add(l); + } + } + catch (ex:Eof) {} + _fileObject.close(); + + detectPackage(); + detectClasses(); + + return _hf; + + } + + private function detectPackage():Void { + var packagePattern = ~/package\s+([a-z.]+)/; + for (line in _lines) { + if (packagePattern.match(line)) { + _package = packagePattern.matched(1); + _hf.filePackage = _package; + return; + } + } + + _package = ""; + } + + private function detectClasses():Void { + var classPattern = ~/public\s+class\s+(\w+)/; + for (line in _lines) { + if (classPattern.match(line)) { + var fullType:String = _package + "." + classPattern.matched(1); + CustomTypes.getInstance().types.add(fullType); + + //Lib.println(fullType); + } + } + } + +} \ No newline at end of file diff --git a/src/net/interaxia/as3tohaxe/translator/Translator.hx b/src/net/interaxia/as3tohaxe/translator/Translator.hx new file mode 100644 index 0000000..7d3b596 --- /dev/null +++ b/src/net/interaxia/as3tohaxe/translator/Translator.hx @@ -0,0 +1,154 @@ +/** + * ... + * @author Jason Miesionczek + */ + +package net.interaxia.as3tohaxe.translator; + +import neko.io.FileInput; +import neko.io.File; +import haxe.io.Eof; +import neko.Lib; +import net.interaxia.as3tohaxe.api.CustomTypes; +import net.interaxia.as3tohaxe.api.FlashAPI; +import net.interaxia.as3tohaxe.HaxeFile; + +class Translator { + + private var _fileObject:FileInput; + private var _lines:List<String>; + private var _output:List<String>; + private var _hf:HaxeFile; + private var _foundPackage:Bool; + + + public function new(inputFile:HaxeFile) { + _lines = new List<String>(); + _output = new List<String>(); + _hf = inputFile; + + + + + for (l in inputFile.lines) { + _lines.add(l); + } + + + } + + public static function compileTypes(f:HaxeFile):Void { + for (line in f.lines) { + checkForTypes(line, f); // this will build the new list of imports + } + } + + public function translate():Void { + Lib.println(_hf.fullPath); + _foundPackage = false; + + for (line in _lines) { + var tempLine:String = line; + if (!_foundPackage) { + tempLine = convertPackage(tempLine); + } + tempLine = convertClassName(tempLine); + tempLine = convertTypes(tempLine); + + Lib.println(tempLine); + } + + } + + private function removeImports(input:String):String { + + } + + private function convertClassName(input:String):String { + var classPattern = ~/public\s+class\s+(\w+)/; + var temp:String = input; + if (classPattern.match(input)) { + var className:String = classPattern.matched(1); + var newName:String = className.charAt(0).toUpperCase() + className.substr(1); + temp = StringTools.replace(temp, className, newName); + } + + return temp; + } + + private function convertPackage(input:String):String { + var temp:String = input; + + if (input.indexOf(_hf.filePackage) >= 0) { + var idx:Int = input.indexOf(" {"); + if (idx >= 0) { + temp = StringTools.replace(temp, " {", ";"); + _foundPackage = true; + } + } + + return temp; + } + + private function convertTypes(input:String):String { + var temp:String = input; + var typeDefPattern = ~/var\s+\w+\s*:\s*(\w+)[;\s]*/; + var typeNewPattern = ~/new\s+(\w+)\(\S*\)/; + + if (typeDefPattern.match(input)) { + var typeToConvert:String = typeDefPattern.matched(1); + var newType:String = CustomTypes.getInstance().matches.get(typeToConvert); + if (newType != null) { + Lib.println(typeToConvert + " => " + newType); + temp = StringTools.replace(input, typeToConvert, newType); + } + } + + if (typeNewPattern.match(input)) { + var typeToConvert:String = typeNewPattern.matched(1); + var newType:String = CustomTypes.getInstance().matches.get(typeToConvert); + if (newType != null) { + Lib.println(typeToConvert + " => " + newType); + temp = StringTools.replace(input, typeToConvert, newType);//typeNewPattern.replace(temp, newType); + } + } + + return temp; + } + + private static function checkForTypes(input:String, hf:HaxeFile):Void { + for (stype in CustomTypes.getInstance().getShortNames()) { + if (input.indexOf(stype) >= 0) { + var out:String = addImport(CustomTypes.getInstance().getFullTypeByName(stype), hf); + CustomTypes.getInstance().matches.set(stype, out.substr(out.lastIndexOf(".")+1)); + } + } + + for (stype in FlashAPI.getInstance().types) { + if (input.indexOf(stype) >= 0) { + addImport(FlashAPI.getInstance().getFullTypeByName(stype), hf); + } + } + } + + private static function addImport(imp:String, hf:HaxeFile):String { + var found:Bool = false; + var out:String = ""; + for (i in hf.imports) { + if (i == imp) { + found = true; + out = i; + break; + } + } + + if (!found) { + hf.imports.add(imp); + out = imp; + Lib.println(" import " + hf.imports.last()); + } + + return out; + } + +} \ No newline at end of file
nomis/airclickd
bda069696c1b936cbe79049a6176cb597b6da5fb
simplify code
diff --git a/Makefile b/Makefile index 4dfc8de..9d37563 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,5 @@ airclickd: airclickd.c Makefile - gcc -o airclickd airclickd.c -O2 -Wall -Werror -ggdb + gcc -D_POSIX_C_SOURCE=200112L -D_ISOC99_SOURCE -D_GNU_SOURCE -O2 -Wall -Wextra -Wshadow -Werror -ggdb -pipe -o airclickd airclickd.c clean: rm -f airclickd diff --git a/airclickd.c b/airclickd.c index 3c0ca9a..b37270c 100644 --- a/airclickd.c +++ b/airclickd.c @@ -1,101 +1,97 @@ /* 2009-06-16 Simon Arlott http://simon.arlott.org/sw/airclickd/ The code is released into the public domain. */ +#include <signal.h> +#include <stdint.h> #include <stdio.h> +#include <stdlib.h> +#include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #define AC_PLAY 0x01 #define AC_VOLUP 0x02 #define AC_VOLDOWN 0x04 #define AC_NEXT 0x08 #define AC_PREV 0x10 /* Protocol format: 03 02 00 xx xx 00 00 00 / \ play 01 01 !play up 02 02 !up down 04 04 down next 08 08 (!next) ^ down prev 10 10 (!prev) ^ (next && down) n/a 20 20 !(prev && next && down) n/a 40 40 n/a n/a 80 80 n/a */ #define AC_LEN 8 #define AC_STATUS 3 -#define AC_SIG1_POS 0 -#define AC_SIG1_VAL 0x03 -#define AC_SIG2_POS 1 -#define AC_SIG2_VAL 0x02 -#define AC_SIG3_POS 2 -#define AC_SIG3_VAL 0x00 -#define AC_SIG4_POS 5 -#define AC_SIG4_VAL 0x00 -#define AC_SIG5_POS 6 -#define AC_SIG5_VAL 0x00 -#define AC_SIG6_POS 7 -#define AC_SIG6_VAL 0x00 - -int run(const char *cmd); +#define AC_PREFIX 0 +#define AC_SUFFIX 5 + +static const uint8_t ac_prefix[] = { 0x03, 0x02, 0x00 }; +static const uint8_t ac_suffix[] = { 0x00, 0x00, 0x00 }; + +static void run(const char *cmd); int main() { - unsigned char last = 0; - unsigned char buf[AC_LEN]; - int status; - int children = 0; + uint_fast8_t last = 0; + uint8_t buf[AC_LEN]; + + if (signal(SIGCHLD, SIG_IGN) == SIG_ERR) { + perror("signal"); + return EXIT_FAILURE; + } /* We'll read 8 bytes (repeatedly) whenever a button is pressed, held down or released. */ - while (read(0, &buf, sizeof(buf)) == sizeof(buf)) { - if (children > 0) { - if (waitpid(-1, &status, WNOHANG) > 0) - children--; - } + while (read(STDIN_FILENO, &buf, sizeof(buf)) == sizeof(buf)) { + uint_fast8_t current = buf[AC_STATUS]; + + if (current == last) + continue; - if (buf[AC_SIG1_POS] != AC_SIG1_VAL) continue; - if (buf[AC_SIG2_POS] != AC_SIG2_VAL) continue; - if (buf[AC_SIG3_POS] != AC_SIG3_VAL) continue; - if (buf[AC_SIG4_POS] != AC_SIG4_VAL) continue; - if (buf[AC_SIG5_POS] != AC_SIG5_VAL) continue; - if (buf[AC_SIG6_POS] != AC_SIG6_VAL) continue; + if (memcmp(buf+AC_PREFIX, ac_prefix, sizeof(ac_prefix)) || memcmp(buf+AC_SUFFIX, ac_suffix, sizeof(ac_suffix))) + continue; - if (!(last & AC_PLAY) && (buf[AC_STATUS] & AC_PLAY)) - children += run("airclick-play"); + if ((current & AC_PLAY) && !(last & AC_PLAY)) + run("airclick-play"); - if (!(last & AC_VOLUP) && (buf[AC_STATUS] & AC_VOLUP)) - children += run("airclick-volup"); + if ((current & AC_VOLUP) && !(last & AC_VOLUP)) + run("airclick-volup"); - if (!(last & AC_VOLDOWN) && (buf[AC_STATUS] & AC_VOLDOWN)) - children += run("airclick-voldown"); + if ((current & AC_VOLDOWN) && !(last & AC_VOLDOWN)) + run("airclick-voldown"); - if (!(last & AC_NEXT) && (buf[AC_STATUS] & AC_NEXT)) - children += run("airclick-next"); + if ((current & AC_NEXT) && !(last & AC_NEXT)) + run("airclick-next"); - if (!(last & AC_PREV) && (buf[AC_STATUS] & AC_PREV)) - children += run("airclick-prev"); + if ((current & AC_PREV) && !(last & AC_PREV)) + run("airclick-prev"); - last = buf[AC_STATUS]; + last = current; } perror("read"); - return 1; + return EXIT_FAILURE; } -int run(const char *cmd) { - if (fork() != 0) return 1; +static void run(const char *cmd) { + if (fork() != 0) return; - close(0); - close(1); - close(2); + close(STDIN_FILENO); + close(STDOUT_FILENO); + close(STDERR_FILENO); execlp(cmd, cmd, NULL); _exit(1); }
nomis/airclickd
da869227c7a58d48baccf7c70cd5be0838afd0b4
simplify protocol explanation
diff --git a/airclickd.c b/airclickd.c index cd8dec3..3c0ca9a 100644 --- a/airclickd.c +++ b/airclickd.c @@ -1,115 +1,101 @@ /* 2009-06-16 Simon Arlott http://simon.arlott.org/sw/airclickd/ The code is released into the public domain. */ #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #define AC_PLAY 0x01 #define AC_VOLUP 0x02 #define AC_VOLDOWN 0x04 #define AC_NEXT 0x08 #define AC_PREV 0x10 /* - Bytes 0, 1, 2: - 03 02 00 - - Byte 3: - 01 play - 02 up - 04 down - 08 next - 10 prev - 20 n/a - 40 n/a - 80 n/a - - Byte 4: - 01 !play - 02 !up - 04 down - 08 (!next) ^ down - 10 (!prev) ^ (next && down) - 20 !(prev && next && down) - 40 n/a - 80 n/a - - Bytes 3, 4, 5: - 00 00 00 + Protocol format: + 03 02 00 xx xx 00 00 00 + / \ + play 01 01 !play + up 02 02 !up + down 04 04 down + next 08 08 (!next) ^ down + prev 10 10 (!prev) ^ (next && down) + n/a 20 20 !(prev && next && down) + n/a 40 40 n/a + n/a 80 80 n/a */ #define AC_LEN 8 #define AC_STATUS 3 #define AC_SIG1_POS 0 #define AC_SIG1_VAL 0x03 #define AC_SIG2_POS 1 #define AC_SIG2_VAL 0x02 #define AC_SIG3_POS 2 #define AC_SIG3_VAL 0x00 #define AC_SIG4_POS 5 #define AC_SIG4_VAL 0x00 #define AC_SIG5_POS 6 #define AC_SIG5_VAL 0x00 #define AC_SIG6_POS 7 #define AC_SIG6_VAL 0x00 int run(const char *cmd); int main() { unsigned char last = 0; unsigned char buf[AC_LEN]; int status; int children = 0; /* We'll read 8 bytes (repeatedly) whenever a button is pressed, held down or released. */ while (read(0, &buf, sizeof(buf)) == sizeof(buf)) { if (children > 0) { if (waitpid(-1, &status, WNOHANG) > 0) children--; } if (buf[AC_SIG1_POS] != AC_SIG1_VAL) continue; if (buf[AC_SIG2_POS] != AC_SIG2_VAL) continue; if (buf[AC_SIG3_POS] != AC_SIG3_VAL) continue; if (buf[AC_SIG4_POS] != AC_SIG4_VAL) continue; if (buf[AC_SIG5_POS] != AC_SIG5_VAL) continue; if (buf[AC_SIG6_POS] != AC_SIG6_VAL) continue; if (!(last & AC_PLAY) && (buf[AC_STATUS] & AC_PLAY)) children += run("airclick-play"); if (!(last & AC_VOLUP) && (buf[AC_STATUS] & AC_VOLUP)) children += run("airclick-volup"); if (!(last & AC_VOLDOWN) && (buf[AC_STATUS] & AC_VOLDOWN)) children += run("airclick-voldown"); if (!(last & AC_NEXT) && (buf[AC_STATUS] & AC_NEXT)) children += run("airclick-next"); if (!(last & AC_PREV) && (buf[AC_STATUS] & AC_PREV)) children += run("airclick-prev"); last = buf[AC_STATUS]; } perror("read"); return 1; } int run(const char *cmd) { if (fork() != 0) return 1; close(0); close(1); close(2); execlp(cmd, cmd, NULL); _exit(1); }
lopnor/Net-Google-Spreadsheets
64add9f8e21047eb0900904844f547a87b09a167
Checking in changes prior to tagging of version 0.1501.
diff --git a/Changes b/Changes index daca94b..40bbfd4 100644 --- a/Changes +++ b/Changes @@ -1,58 +1,61 @@ Revision history for Perl extension Net::Google::Spreadsheets +0.1501 Mon Apr 30 09:05:00 2012 + - update link URLs for documentations by google (#76767) + 0.15 Fri Apr 06 22:20:00 2012 - follow Net::Google::DataAPI changes and fix broken test 0.14 Sun Aug 15 13:15:00 2010 - less dependencies 0.13 Tue Aug 10 10:30:00 2010 - change default feed URL to use SSL, since Google is returning those now (thanks to dwc) 0.12 Sun Jun 07 13:00:00 2010 - fixed getting table error (thanks to sartak) - added documentations on tables, rows (thanks to siguc) - fixed num_rows property of Table was not working (thanks to Yan Wong, #57540) 0.11 Thu Apr 22 16:10:00 2010 - added documentation on deleteing items (thanks to siguc) 0.10 Mon Mar 15 23:49:00 2010 - update dependencies (Mouse 0.51, Net::Google::DataAPI 0.17) 0.09 Sun Mar 07 23:27:00 2010 - Fix spreadsheet key changes (thanks to Colin Magee) 0.08 Thu Dec 31 19:20:30 2009 - follow Net::Google::DataAPI changes - update POD 0.07 Fri Dec 22 22:53:34 2009 - now uses Net::Google::DataAPI - AuthSub and OAuth support via Net::Google::DataAPI - now uses Any::Moose 0.06 Thu Aug 20 23:21:35 2009 - Refactored internals 0.06_01 Mon Arg 16 16:01:27 2009 - Supports Google Spreadsheets API version 3.0 - Add table and record feeds supports - Better error handlings (no more redirects, captures xml parse error, and more) - Refactored internals 0.05 Sun Aug 15 09:47:50 2009 - Fix Moose attribute problem #48627 (thanks to Eric Celeste, IMALPASS) 0.04 Wed Apr 15 09:22:59 2009 - Updated POD (thanks to Mr. Grue) 0.03 Sun Apr 05 13:22:21 2009 - param method for Net::Google::Spreadsheets::Row (thanks to Mr. Grue) 0.02 Sat Apr 04 22:32:40 2009 - Crypt::SSLeay dependency - Better error message on login failure (thanks to Mr. Grue) 0.01 Tue Dec 16 23:52:25 2008 - original version diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index 5dc9581..cb0e6c7 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,353 +1,351 @@ package Net::Google::Spreadsheets; use 5.008001; use Any::Moose; use Net::Google::DataAPI; use Net::Google::AuthSub; use Net::Google::DataAPI::Auth::AuthSub; -our $VERSION = '0.15'; +our $VERSION = '0.1501'; with 'Net::Google::DataAPI::Role::Service'; has gdata_version => ( is => 'ro', isa => 'Str', default => '3.0' ); has namespaces => ( is => 'ro', isa => 'HashRef', default => sub { { gs => 'http://schemas.google.com/spreadsheets/2006', gsx => 'http://schemas.google.com/spreadsheets/2006/extended', batch => 'http://schemas.google.com/gdata/batch', } }, ); has username => (is => 'ro', isa => 'Str'); has password => (is => 'ro', isa => 'Str'); has account_type => (is => 'ro', isa => 'Str', required => 1, default => 'HOSTED_OR_GOOGLE'); has source => (is => 'ro', isa => 'Str', required => 1, default => __PACKAGE__ . '-' . $VERSION); sub _build_auth { my ($self) = @_; my $authsub = Net::Google::AuthSub->new( source => $self->source, service => 'wise', account_type => $self->account_type, ); my $res = $authsub->login( $self->username, $self->password ); unless ($res && $res->is_success) { die 'Net::Google::AuthSub login failed'; } return Net::Google::DataAPI::Auth::AuthSub->new( authsub => $authsub, ); } feedurl spreadsheet => ( default => 'https://spreadsheets.google.com/feeds/spreadsheets/private/full', entry_class => 'Net::Google::Spreadsheets::Spreadsheet', can_add => 0, ); around spreadsheets => sub { my ($next, $self, $args) = @_; my @result = $next->($self, $args); if (my $key = $args->{key}) { @result = grep {$_->key eq $key} @result; } return @result; }; sub BUILD { my $self = shift; $self->auth; } __PACKAGE__->meta->make_immutable; no Any::Moose; no Net::Google::DataAPI; 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, {row => 1, col => 4, input_value => 'age'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', - mail => '[email protected]', + mail => '[email protected]', age => '33', } ); # fetch rows my @rows = $worksheet->rows; # or fetch rows with query @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', - mail => '[email protected]', + mail => '[email protected]', } ); # delete the row $row->delete; # delete the worksheet $worksheet->delete; # create a table my $table = $spreadsheet->add_table( { worksheet => $new_worksheet, columns => ['name', 'nick', 'mail address', 'age'], } ); # add a record my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', - 'mail address' => '[email protected]', + 'mail address' => '[email protected]', age => '33', } ); # find a record my $found = $table->record( { - sq => '"mail address" = "[email protected]"' + sq => '"mail address" = "[email protected]"' } ); # delete it $found->delete; # delete table $table->delete; =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 2 =item * username Username for Google. This should be full email address format like '[email protected]'. =item * password Password corresponding to the username. =item * source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 2 =item * title title of the spreadsheet. =item * title-exact whether title search should match exactly or not. =item * key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 AUTHORIZATIONS you can optionally pass auth object argument when initializing Net::Google::Spreadsheets instance. If you want to use AuthSub mechanism, make Net::Google::DataAPI::Auth::AuthSub object and path it to the constructor: my $authsub = Net::Google::AuthSub->new; $authsub->auth(undef, $session_token); my $service = Net::Google::Spreadsheet->new( auth => $authsub ); In OAuth case, like this: my $oauth = Net::Google::DataAPI::Auth::OAuth->new( consumer_key => 'consumer.example.com', consumer_secret => 'mys3cr3t', callback => 'http://consumer.example.com/callback', ); $oauth->get_request_token; my $url = $oauth->get_authorize_token_url; # show the url to the user and get the $verifier value $oauth->get_access_token({verifier => $verifier}); my $service = Net::Google::Spreadsheet->new( auth => $oauth ); =head1 TESTING To test this module, you have to prepare as below. =over 2 =item * create a spreadsheet by hand Go to L<http://docs.google.com> and create a spreadsheet. =item * set SPREADSHEET_TITLE environment variable export SPREADSHEET_TITLE='my test spreadsheet' or so. =item * set username and password for google.com via Config::Pit install Config::Pit and type ppit set google.com then some editor comes up and type your username and password like --- username: [email protected] password: foobarbaz =item * run tests as always, perl Makefile.PL make make test =back =head1 AUTHOR -Nobuo Danjou E<lt>[email protected]<gt> +Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO -L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> - -L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> +L<https://developers.google.com/google-apps/spreadsheets/> L<Net::Google::AuthSub> L<Net::Google::DataAPI> L<Net::OAuth> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Record> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Net/Google/Spreadsheets/Cell.pm b/lib/Net/Google/Spreadsheets/Cell.pm index 1b05a50..4fdab25 100644 --- a/lib/Net/Google/Spreadsheets/Cell.pm +++ b/lib/Net/Google/Spreadsheets/Cell.pm @@ -1,123 +1,121 @@ package Net::Google::Spreadsheets::Cell; use Any::Moose; use XML::Atom::Util qw(first); with 'Net::Google::DataAPI::Role::Entry'; has content => ( isa => 'Str', is => 'ro', ); has row => ( isa => 'Int', is => 'ro', ); has col => ( isa => 'Int', is => 'ro', ); has input_value => ( isa => 'Str', is => 'rw', trigger => sub {$_[0]->update}, ); after from_atom => sub { my ($self) = @_; my $elem = first( $self->elem, $self->ns('gs')->{uri}, 'cell'); $self->{row} = $elem->getAttribute('row'); $self->{col} = $elem->getAttribute('col'); $self->{input_value} = $elem->getAttribute('inputValue'); $self->{content} = $elem->textContent || ''; }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->ns('gs'), 'cell', '', { row => $self->row, col => $self->col, inputValue => $self->input_value, } ); my $link = XML::Atom::Link->new; $link->rel('edit'); $link->type('application/atom+xml'); $link->href($self->editurl); $entry->link($link); $entry->id($self->id); return $entry; }; __PACKAGE__->meta->make_immutable; no Any::Moose; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Cell - A representation class for Google Spreadsheet cell. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a cell my $cell = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->cell( { col => 1, row => 1, } ); # update a cell $cell->input_value('new value'); # get the content of a cell my $value = $cell->content; =head1 ATTRIBUTES =head2 input_value Rewritable attribute. You can set formula like '=A1+B1' or so. =head2 content Read only attribute. You can get the result of formula. =head1 SEE ALSO -L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> - -L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> +L<https://developers.google.com/google-apps/spreadsheets/> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR -Nobuo Danjou E<lt>[email protected]<gt> +Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Record.pm b/lib/Net/Google/Spreadsheets/Record.pm index e7b75b6..fdbb727 100644 --- a/lib/Net/Google/Spreadsheets/Record.pm +++ b/lib/Net/Google/Spreadsheets/Record.pm @@ -1,137 +1,135 @@ package Net::Google::Spreadsheets::Record; use Any::Moose; use XML::Atom::Util qw(nodelist); with 'Net::Google::DataAPI::Role::Entry', 'Net::Google::DataAPI::Role::HasContent'; after from_atom => sub { my ($self) = @_; for my $node (nodelist($self->elem, $self->ns('gs')->{uri}, 'field')) { $self->content->{$node->getAttribute('name')} = $node->textContent; } }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->content}) { $entry->add($self->ns('gs'), 'field', $value, {name => $key}); } return $entry; }; __PACKAGE__->meta->make_immutable; no Any::Moose; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Record - A representation class for Google Spreadsheet record. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a record my $record = $service->spreadsheet( { title => 'list for new year cards', } )->table( { title => 'addressbook', } )->record( { sq => 'id = 1000', } ); # get the content of a row my $hashref = $record->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $record->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $record->param('name'); # returns 'Nobuo Danjou' # you can also get it via content like this: my $value_via_content = $record->content->{name}; my $newval = $record->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new record value (with all fields) my $hashref2 = $record->param; # same as $record->content; # setting whole new content $record->content( { id => 8080, address => 'nowhere', zip => '999-9999', name => 'nowhere man' } ); # delete a record $record->delete; =head1 METHODS =head2 param sets and gets content value. =head2 delete deletes the record. =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO -L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> - -L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> +L<https://developers.google.com/google-apps/spreadsheets/> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Row> =head1 AUTHOR -Nobuo Danjou E<lt>[email protected]<gt> +Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Row.pm b/lib/Net/Google/Spreadsheets/Row.pm index 3fda427..9a2b9d2 100644 --- a/lib/Net/Google/Spreadsheets/Row.pm +++ b/lib/Net/Google/Spreadsheets/Row.pm @@ -1,173 +1,171 @@ package Net::Google::Spreadsheets::Row; use Any::Moose; use Net::Google::DataAPI; use XML::Atom::Util qw(nodelist); with 'Net::Google::DataAPI::Role::Entry', 'Net::Google::DataAPI::Role::HasContent'; after from_atom => sub { my ($self) = @_; for my $node (nodelist($self->elem, $self->ns('gsx')->{uri}, '*')) { $self->content->{$node->localname} = $node->textContent; } }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->content}) { $entry->set($self->ns('gsx'), $key, $value); } return $entry; }; __PACKAGE__->meta->make_immutable; no Any::Moose; no Net::Google::DataAPI; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Row - A representation class for Google Spreadsheet row. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a row my $row = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->row( { sq => 'id = 1000' } ); # get the content of a row my $hashref = $row->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $row->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $row->param('name'); # returns 'Nobuo Danjou' # it's same by getting via param method without args, or content method: my $value_by_param = $row->param->{name}; my $value_by_content = $row->content->{name}; my $newval = $row->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new row value (with all fields) my $hashref2 = $row->param; # same as $row->content; # delete the row $row->delete; =head1 METHODS =head2 param sets and gets content value. =head2 delete deletes the row. =head1 CAVEATS Space characters in hash key of rows will be removed when you access rows. See below. my $ws = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'})->worksheet(1); $ws->batchupdate_cell( {col => 1,row => 1, input_value => 'name'}, {col => 2,row => 1, input_value => 'mail address'}, ); $ws->add_row( { name => 'my name', mailaddress => '[email protected]', # above passes, below fails. # 'mail address' => '[email protected]', } ); Instead, Net::Google::Spreadsheets::Table and Net::Google::Spreadsheets::Record allows space characters in column name. my $s = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'}); my $t = $s->add_table( { worksheet => $s->worksheet(1), columns => ['name', 'mail address'], } ); $t->add_record( { name => 'my name', 'mail address' => '[email protected]', } ); =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. So it's the same thing to get the value with param method or content attribute. my $value = $row->param('foo'); # it's same my $value2 = $row->content->{'foo'}; =head1 SEE ALSO -L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> - -L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> +L<https://developers.google.com/google-apps/spreadsheets/> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR -Nobuo Danjou E<lt>[email protected]<gt> +Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Spreadsheet.pm b/lib/Net/Google/Spreadsheets/Spreadsheet.pm index b79b0c1..dffa03c 100644 --- a/lib/Net/Google/Spreadsheets/Spreadsheet.pm +++ b/lib/Net/Google/Spreadsheets/Spreadsheet.pm @@ -1,252 +1,250 @@ package Net::Google::Spreadsheets::Spreadsheet; use Any::Moose; use Net::Google::DataAPI; with 'Net::Google::DataAPI::Role::Entry'; use URI; has title => ( is => 'ro', isa => 'Str', lazy_build => 1, ); entry_has key => ( isa => 'Str', is => 'ro', from_atom => sub { my ($self, $atom) = @_; my ($link) = grep { $_->rel eq 'alternate' && $_->type eq 'text/html' } $atom->link; return {URI->new($link->href)->query_form}->{key}; }, ); feedurl worksheet => ( entry_class => 'Net::Google::Spreadsheets::Worksheet', as_content_src => 1, ); feedurl table => ( entry_class => 'Net::Google::Spreadsheets::Table', rel => 'http://schemas.google.com/spreadsheets/2006#tablesfeed', ); __PACKAGE__->meta->make_immutable; no Any::Moose; no Net::Google::DataAPI; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Spreadsheet - Representation of spreadsheet. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # create a worksheet my $worksheet = $spreadsheet->add_worksheet( { title => 'foobar', col_count => 10, row_count => 100, } ); # list worksheets my @ws = $spreadsheet->worksheets; # find a worksheet my $ws = $spreadsheet->worksheet({title => 'fooba'}); # create a table my $table = $spreadsheet->add_table( { title => 'sample table', worksheet => $worksheet, columns => ['id', 'username', 'mail', 'password'], } ); # list tables my @t = $spreadsheet->tables; # find a worksheet my $t = $spreadsheet->table({title => 'sample table'}); =head1 METHODS =head2 worksheets(\%condition) Returns a list of Net::Google::Spreadsheets::Worksheet objects. Acceptable arguments are: =over 2 =item * title =item * title-exact =back =head2 worksheet(\%condition) Returns first item of worksheets(\%condition) if available. =head2 add_worksheet(\%attribuets) Creates new worksheet and returns a Net::Google::Spreadsheets::Worksheet object representing it. Arguments (all optional) are: =over 2 =item * title =item * col_count =item * row_count =back =head2 tables(\%condition) Returns a list of Net::Google::Spreadsheets::Table objects. Acceptable arguments are: =over 2 =item * title =item * title-exact =back =head2 table(\%condition) Returns first item of tables(\%condition) if available. =head2 add_table(\%attribuets) Creates new table and returns a Net::Google::Spreadsheets::Table object representing it. Arguments are: =over 2 =item * title (optional) =item * summary (optional) =item * worksheet Worksheet where the table lives. worksheet instance or the title. =item * header (optional, default = 1) Row number of header =item * start_row (optional, default = 2) The index of the first row of the data section. =item * num_rows (optional, default = 0) Number of rows of the data section initially made. =item * insertion_mode (optional, default = 'overwrite') Insertion mode. 'insert' inserts new row into the worksheet when creating record, 'overwrite' tries to use existing rows in the worksheet. =item * columns Columns of the table. you can specify them as hashref, arrayref, arrayref of hashref. $ss->add_table( { worksheet => $ws, columns => [ {index => 1, name => 'foo'}, {index => 2, name => 'bar'}, {index => 3, name => 'baz'}, ], } ); $ss->add_table( { worksheet => $ws, columns => { A => 'foo', B => 'bar', C => 'baz', } } ); $ss->add_table( { worksheet => $ws, columns => ['foo', 'bar', 'baz'], } ); 'index' of the first case and hash key of the second case is column index of the worksheet. In the third case, the columns is automatically placed to the columns of the worksheet from 'A' to 'Z' order. =back =head1 DELETING A SPREADSHEET To delete a spreadsheet, use L<Net::Google::DocumentsList>. my $docs = Net::Google::DocumentsList->new( username => '[email protected]', password => 'mypassword' ); $docs->item({resource_id => 'spreadsheet:'. $ss->key})->delete; =head1 SEE ALSO -L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> - -L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> +L<https://developers.google.com/google-apps/spreadsheets/> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Table> L<Net::Google::DocumentsList> =head1 AUTHOR -Nobuo Danjou E<lt>[email protected]<gt> +Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Table.pm b/lib/Net/Google/Spreadsheets/Table.pm index 78aba39..2265ac9 100644 --- a/lib/Net/Google/Spreadsheets/Table.pm +++ b/lib/Net/Google/Spreadsheets/Table.pm @@ -1,241 +1,239 @@ package Net::Google::Spreadsheets::Table; use Any::Moose; use Any::Moose '::Util::TypeConstraints'; use Net::Google::DataAPI; use XML::Atom::Util qw(nodelist first create_element); use Net::Google::Spreadsheets::Worksheet; use Net::Google::Spreadsheets::Record; with 'Net::Google::DataAPI::Role::Entry'; subtype 'ColumnList' => as 'ArrayRef[Net::Google::Spreadsheets::Table::Column]'; coerce 'ColumnList' => from 'ArrayRef[HashRef]' => via { [ map {Net::Google::Spreadsheets::Table::Column->new($_)} @$_ ] }; coerce 'ColumnList' => from 'ArrayRef[Str]' => via { my @c; my $index = 0; for my $value (@$_) { push @c, Net::Google::Spreadsheets::Table::Column->new( index => ++$index, name => $value, ); } \@c; }; coerce 'ColumnList' => from 'HashRef' => via { my @c; while (my ($key, $value) = each(%$_)) { push @c, Net::Google::Spreadsheets::Table::Column->new( index => $key, name => $value, ); } \@c; }; subtype 'WorksheetName' => as 'Str'; coerce 'WorksheetName' => from 'Net::Google::Spreadsheets::Worksheet' => via { $_->title }; feedurl record => ( entry_class => 'Net::Google::Spreadsheets::Record', arg_builder => sub { my ($self, $args) = @_; return {content => $args}; }, as_content_src => 1, ); has summary => ( is => 'rw', isa => 'Str' ); has worksheet => ( is => 'ro', isa => 'WorksheetName', coerce => 1 ); has header => ( is => 'ro', isa => 'Int', required => 1, default => 1 ); has start_row => ( is => 'ro', isa => 'Int', required => 1, default => 2 ); has num_rows => ( is => 'ro', isa => 'Int' ); has columns => ( is => 'ro', isa => 'ColumnList', coerce => 1 ); has insertion_mode => ( is => 'ro', isa => (enum ['insert', 'overwrite']), default => 'overwrite' ); after from_atom => sub { my ($self) = @_; my $gsns = $self->ns('gs')->{uri}; my $elem = $self->elem; $self->{summary} = $self->atom->summary; $self->{worksheet} = first( $elem, $gsns, 'worksheet')->getAttribute('name'); $self->{header} = first( $elem, $gsns, 'header')->getAttribute('row'); my @columns; my $data = first($elem, $gsns, 'data'); $self->{insertion_mode} = $data->getAttribute('insertionMode'); $self->{start_row} = $data->getAttribute('startRow'); $self->{num_rows} = $data->getAttribute('numRows'); for (nodelist($data, $gsns, 'column')) { push @columns, Net::Google::Spreadsheets::Table::Column->new( index => $_->getAttribute('index'), name => $_->getAttribute('name'), ); } $self->{columns} = \@columns; }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); my $gsns = $self->ns('gs')->{uri}; $entry->summary($self->summary) if $self->summary; $entry->set($gsns, 'worksheet', '', {name => $self->worksheet}); $entry->set($gsns, 'header', '', {row => $self->header}); my $data = create_element($gsns, 'data'); $data->setAttribute(startRow => $self->start_row); $data->setAttribute(insertionMode => $self->insertion_mode); $data->setAttribute(numRows => $self->num_rows) if $self->num_rows; for ( @{$self->columns} ) { my $column = create_element($gsns, 'column'); $column->setAttribute(index => $_->index); $column->setAttribute(name => $_->name); $data->appendChild($column); } $entry->set($gsns, 'data', $data); return $entry; }; __PACKAGE__->meta->make_immutable; no Any::Moose; no Any::Moose '::Util::TypeConstraints'; no Net::Google::DataAPI; package # hide from PAUSE Net::Google::Spreadsheets::Table::Column; use Any::Moose; has 'index' => ( is => 'ro', isa => 'Str' ); has 'name' => ( is => 'ro', isa => 'Str' ); __PACKAGE__->meta->make_immutable; no Any::Moose; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Table - A representation class for Google Spreadsheet table. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a table my $table = $service->spreadsheet( { title => 'list for new year cards', } )->table( { title => 'sample table', } ); # create a record my $r = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', - mail => '[email protected]', + mail => '[email protected]', age => '33', } ); # get records my @records = $table->records; # search records @records = $table->records({sq => 'age > 20'}); # search a record my $record = $table->record({sq => 'name = "Nobuo Danjou"'}); =head1 METHODS =head2 records(\%condition) Returns a list of Net::Google::Spreadsheets::Record objects. Acceptable arguments are: =over 2 =item * sq Structured query on the full text in the worksheet. see the URL below for detail. =item * orderby Set column name to use for ordering. =item * reverse Set 'true' or 'false'. The default is 'false'. It reverses the order. =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#RecordParameters> for details. =head2 record(\%condition) Returns first item of records(\%condition) if available. =head2 add_record(\%contents) Creates new record and returns a Net::Google::Spreadsheets::Record object representing it. Arguments are contents of a row as a hashref. my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', - mail => '[email protected]', + mail => '[email protected]', age => '33', } ); =head1 CAVEATS You can access to the table structure and records only from the Google Spreadsheets API. It means you can't create tables, add records or delete tables via web interface. It will make some problems if you want to access the data both from API and web interface. In that case, you should use $worksheets->row(s) methods instead. See the documents below for details: L<http://code.google.com/intl/en/apis/spreadsheets/data/3.0/developers_guide_protocol.html#TableFeeds> =head1 SEE ALSO -L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> - -L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> +L<https://developers.google.com/google-apps/spreadsheets/> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Record> =head1 AUTHOR -Nobuo Danjou E<lt>[email protected]<gt> +Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Worksheet.pm b/lib/Net/Google/Spreadsheets/Worksheet.pm index e6afba6..5bef1d9 100644 --- a/lib/Net/Google/Spreadsheets/Worksheet.pm +++ b/lib/Net/Google/Spreadsheets/Worksheet.pm @@ -1,260 +1,258 @@ package Net::Google::Spreadsheets::Worksheet; use Any::Moose; use Net::Google::DataAPI; with 'Net::Google::DataAPI::Role::Entry'; use Carp; use Net::Google::Spreadsheets::Cell; use XML::Atom::Util qw(first); feedurl row => ( entry_class => 'Net::Google::Spreadsheets::Row', as_content_src => 1, arg_builder => sub { my ($self, $args) = @_; return {content => $args}; }, ); feedurl cell => ( entry_class => 'Net::Google::Spreadsheets::Cell', can_add => 0, rel => 'http://schemas.google.com/spreadsheets/2006#cellsfeed', query_builder => sub { my ($self, $args) = @_; if (my $col = delete $args->{col}) { $args->{'max-col'} = $col; $args->{'min-col'} = $col; $args->{'return-empty'} = 'true'; } if (my $row = delete $args->{row}) { $args->{'max-row'} = $row; $args->{'min-row'} = $row; $args->{'return-empty'} = 'true'; } return $args; }, ); entry_has row_count => ( isa => 'Int', is => 'rw', default => 100, tagname => 'rowCount', ns => 'gs', ); entry_has col_count => ( isa => 'Int', is => 'rw', default => 20, tagname => 'colCount', ns => 'gs', ); __PACKAGE__->meta->make_immutable; sub batchupdate_cell { my ($self, @args) = @_; my $feed = XML::Atom::Feed->new; for ( @args ) { my $id = sprintf("%s/R%sC%s",$self->cell_feedurl, $_->{row}, $_->{col}); $_->{id} = $_->{editurl} = $id; $_->{container} = $self, my $entry = Net::Google::Spreadsheets::Cell->new($_)->to_atom; $entry->set($self->ns('batch'), operation => '', {type => 'update'}); $entry->set($self->ns('batch'), id => $id); $feed->add_entry($entry); } my $res_feed = $self->service->post( $self->cell_feedurl."/batch", $feed, {'If-Match' => '*'} ); $self->sync; return map { Net::Google::Spreadsheets::Cell->new( atom => $_, container => $self, ) } grep { my $node = first( $_->elem, $self->ns('batch')->{uri}, 'status' ); $node->getAttribute('code') == 200; } $res_feed->entries; } no Any::Moose; no Net::Google::DataAPI; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Worksheet - Representation of worksheet. =head1 SYNOPSIS my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); my $ss = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); my $worksheet = $ss->worksheet({title => 'Sheet1'}); # update cell by batch request $worksheet->batchupdate_cell( {col => 1, row => 1, input_value => 'name'}, {col => 2, row => 1, input_value => 'nick'}, {col => 3, row => 1, input_value => 'mail'}, {col => 4, row => 1, input_value => 'age'}, ); # get a cell object my $cell = $worksheet->cell({col => 1, row => 1}); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', - mail => '[email protected]', + mail => '[email protected]', age => '33', } ); # get rows my @rows = $worksheet->rows; # search rows @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # delete the worksheet # Note that this will fail if the worksheet is the only one # within the spreadsheet. $worksheet->delete; =head1 METHODS =head2 rows(\%condition) Returns a list of Net::Google::Spreadsheets::Row objects. Acceptable arguments are: =over 2 =item * sq Structured query on the full text in the worksheet. see the URL below for detail. =item * orderby Set column name to use for ordering. =item * reverse Set 'true' or 'false'. The default is 'false'. =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#ListParameters> for details. Note that 'the first row of the worksheet' you can see with the browser is 'header' for the rows, so you can't get it with this method. Use cell(s) method instead if you need to access them. =head2 row(\%condition) Returns first item of rows(\%condition) if available. =head2 add_row(\%contents) Creates new row and returns a Net::Google::Spreadsheets::Row object representing it. Arguments are contents of a row as a hashref. my $row = $ws->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', - mail => '[email protected]', + mail => '[email protected]', age => '33', } ); =head2 cells(\%args) Returns a list of Net::Google::Spreadsheets::Cell objects. Acceptable arguments are: =over 2 =item * min-row =item * max-row =item * min-col =item * max-col =item * range =item * return-empty =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#CellParameters> for details. =head2 cell(\%args) Returns Net::Google::Spreadsheets::Cell object. Arguments are: =over 2 =item * col =item * row =back =head2 batchupdate_cell(@args) update multiple cells with a batch request. Pass a list of hash references containing: =over 2 =item * col =item * row =item * input_value =back =head2 delete Deletes the worksheet. Note that this will fail if the worksheet is only one within the spreadsheet. =head1 SEE ALSO -L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> - -L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> +L<https://developers.google.com/google-apps/spreadsheets/> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR -Nobuo Danjou E<lt>[email protected]<gt> +Nobuo Danjou E<lt>[email protected]<gt> =cut
lopnor/Net-Google-Spreadsheets
12125d8df97a897f1479afdf18506825994eba73
Checking in changes prior to tagging of version 0.15.
diff --git a/.gitignore b/.gitignore index 941c1e9..5bac70f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,9 @@ MANIFEST.bak META.yml Makefile Makefile.old blib inc pm_to_blib cover_db +MYMETA.* diff --git a/Changes b/Changes index a5b2fc7..daca94b 100644 --- a/Changes +++ b/Changes @@ -1,55 +1,58 @@ Revision history for Perl extension Net::Google::Spreadsheets +0.15 Fri Apr 06 22:20:00 2012 + - follow Net::Google::DataAPI changes and fix broken test + 0.14 Sun Aug 15 13:15:00 2010 - less dependencies 0.13 Tue Aug 10 10:30:00 2010 - change default feed URL to use SSL, since Google is returning those now (thanks to dwc) 0.12 Sun Jun 07 13:00:00 2010 - fixed getting table error (thanks to sartak) - added documentations on tables, rows (thanks to siguc) - fixed num_rows property of Table was not working (thanks to Yan Wong, #57540) 0.11 Thu Apr 22 16:10:00 2010 - added documentation on deleteing items (thanks to siguc) 0.10 Mon Mar 15 23:49:00 2010 - update dependencies (Mouse 0.51, Net::Google::DataAPI 0.17) 0.09 Sun Mar 07 23:27:00 2010 - Fix spreadsheet key changes (thanks to Colin Magee) 0.08 Thu Dec 31 19:20:30 2009 - follow Net::Google::DataAPI changes - update POD 0.07 Fri Dec 22 22:53:34 2009 - now uses Net::Google::DataAPI - AuthSub and OAuth support via Net::Google::DataAPI - now uses Any::Moose 0.06 Thu Aug 20 23:21:35 2009 - Refactored internals 0.06_01 Mon Arg 16 16:01:27 2009 - Supports Google Spreadsheets API version 3.0 - Add table and record feeds supports - Better error handlings (no more redirects, captures xml parse error, and more) - Refactored internals 0.05 Sun Aug 15 09:47:50 2009 - Fix Moose attribute problem #48627 (thanks to Eric Celeste, IMALPASS) 0.04 Wed Apr 15 09:22:59 2009 - Updated POD (thanks to Mr. Grue) 0.03 Sun Apr 05 13:22:21 2009 - param method for Net::Google::Spreadsheets::Row (thanks to Mr. Grue) 0.02 Sat Apr 04 22:32:40 2009 - Crypt::SSLeay dependency - Better error message on login failure (thanks to Mr. Grue) 0.01 Tue Dec 16 23:52:25 2008 - original version diff --git a/MANIFEST b/MANIFEST index 4a0b2d1..8c2d915 100644 --- a/MANIFEST +++ b/MANIFEST @@ -1,49 +1,38 @@ Changes inc/Module/Install.pm inc/Module/Install/Any/Moose.pm inc/Module/Install/AuthorTests.pm inc/Module/Install/Base.pm inc/Module/Install/Can.pm inc/Module/Install/Fetch.pm -inc/Module/Install/Include.pm inc/Module/Install/Makefile.pm inc/Module/Install/Metadata.pm inc/Module/Install/Repository.pm -inc/Module/Install/TestBase.pm inc/Module/Install/Win32.pm inc/Module/Install/WriteAll.pm -inc/Spiffy.pm -inc/Test/Base.pm -inc/Test/Base/Filter.pm -inc/Test/Builder.pm -inc/Test/Builder/Module.pm -inc/Test/Exception.pm -inc/Test/MockModule.pm -inc/Test/MockObject.pm -inc/Test/More.pm lib/Net/Google/Spreadsheets.pm lib/Net/Google/Spreadsheets/Cell.pm lib/Net/Google/Spreadsheets/Record.pm lib/Net/Google/Spreadsheets/Row.pm lib/Net/Google/Spreadsheets/Spreadsheet.pm lib/Net/Google/Spreadsheets/Table.pm lib/Net/Google/Spreadsheets/Worksheet.pm Makefile.PL MANIFEST This list of files META.yml README t/00_compile.t t/01_instanciate.t t/02_spreadsheet.t t/03_worksheet.t t/04_cell.t t/05_row.t t/06_table.t t/07_record.t t/08_error.t t/Util.pm xt/01_podspell.t xt/02_perlcritic.t xt/03_pod.t xt/04_synopsis.t xt/perlcriticrc diff --git a/MANIFEST.SKIP b/MANIFEST.SKIP index f32e539..a9ec017 100644 --- a/MANIFEST.SKIP +++ b/MANIFEST.SKIP @@ -1,22 +1,24 @@ \bRCS\b \bCVS\b ^MANIFEST\. ^Makefile$ +^MYMETA.yml$ +^MYMETA.json$ ~$ ^# \.old$ ^blib/ ^pm_to_blib ^MakeMaker-\d \.gz$ \.cvsignore \.gitignore ^t/9\d_.*\.t ^t/perlcritic ^tools/ \.svn/ \.git/ ^[^/]+\.yaml$ ^[^/]+\.pl$ ^\.shipit$ ^cover_db/ diff --git a/Makefile.PL b/Makefile.PL index 7c2fd9c..a048433 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,26 +1,24 @@ use inc::Module::Install; name 'Net-Google-Spreadsheets'; all_from 'lib/Net/Google/Spreadsheets.pm'; requires 'Carp'; requires 'XML::Atom'; requires 'Net::Google::AuthSub'; -requires 'Net::Google::DataAPI' => '0.21'; +requires 'Net::Google::DataAPI' => '0.27'; requires 'URI'; requires_any_moose( prefer => 'Mouse', moose => '0.56', mouse => '0.51', ); tests_recursive; author_tests 'xt'; build_requires 'Test::More' => '0.88'; build_requires 'Test::Exception'; build_requires 'Test::MockModule'; build_requires 'Test::MockObject'; -use_test_base; -auto_include; auto_set_repository; WriteAll; diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index 3f7c91d..5dc9581 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,353 +1,353 @@ package Net::Google::Spreadsheets; use 5.008001; use Any::Moose; use Net::Google::DataAPI; use Net::Google::AuthSub; use Net::Google::DataAPI::Auth::AuthSub; -our $VERSION = '0.14'; +our $VERSION = '0.15'; with 'Net::Google::DataAPI::Role::Service'; has gdata_version => ( is => 'ro', isa => 'Str', default => '3.0' ); has namespaces => ( is => 'ro', isa => 'HashRef', default => sub { { gs => 'http://schemas.google.com/spreadsheets/2006', gsx => 'http://schemas.google.com/spreadsheets/2006/extended', batch => 'http://schemas.google.com/gdata/batch', } }, ); has username => (is => 'ro', isa => 'Str'); has password => (is => 'ro', isa => 'Str'); has account_type => (is => 'ro', isa => 'Str', required => 1, default => 'HOSTED_OR_GOOGLE'); has source => (is => 'ro', isa => 'Str', required => 1, default => __PACKAGE__ . '-' . $VERSION); sub _build_auth { my ($self) = @_; my $authsub = Net::Google::AuthSub->new( source => $self->source, service => 'wise', account_type => $self->account_type, ); my $res = $authsub->login( $self->username, $self->password ); unless ($res && $res->is_success) { die 'Net::Google::AuthSub login failed'; } return Net::Google::DataAPI::Auth::AuthSub->new( authsub => $authsub, ); } feedurl spreadsheet => ( default => 'https://spreadsheets.google.com/feeds/spreadsheets/private/full', entry_class => 'Net::Google::Spreadsheets::Spreadsheet', can_add => 0, ); around spreadsheets => sub { my ($next, $self, $args) = @_; my @result = $next->($self, $args); if (my $key = $args->{key}) { @result = grep {$_->key eq $key} @result; } return @result; }; sub BUILD { my $self = shift; $self->auth; } __PACKAGE__->meta->make_immutable; no Any::Moose; no Net::Google::DataAPI; 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, {row => 1, col => 4, input_value => 'age'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # fetch rows my @rows = $worksheet->rows; # or fetch rows with query @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); # delete the row $row->delete; # delete the worksheet $worksheet->delete; # create a table my $table = $spreadsheet->add_table( { worksheet => $new_worksheet, columns => ['name', 'nick', 'mail address', 'age'], } ); # add a record my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', 'mail address' => '[email protected]', age => '33', } ); # find a record my $found = $table->record( { sq => '"mail address" = "[email protected]"' } ); # delete it $found->delete; # delete table $table->delete; =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 2 =item * username Username for Google. This should be full email address format like '[email protected]'. =item * password Password corresponding to the username. =item * source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 2 =item * title title of the spreadsheet. =item * title-exact whether title search should match exactly or not. =item * key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 AUTHORIZATIONS you can optionally pass auth object argument when initializing Net::Google::Spreadsheets instance. If you want to use AuthSub mechanism, make Net::Google::DataAPI::Auth::AuthSub object and path it to the constructor: my $authsub = Net::Google::AuthSub->new; $authsub->auth(undef, $session_token); my $service = Net::Google::Spreadsheet->new( auth => $authsub ); In OAuth case, like this: my $oauth = Net::Google::DataAPI::Auth::OAuth->new( consumer_key => 'consumer.example.com', consumer_secret => 'mys3cr3t', callback => 'http://consumer.example.com/callback', ); $oauth->get_request_token; my $url = $oauth->get_authorize_token_url; # show the url to the user and get the $verifier value $oauth->get_access_token({verifier => $verifier}); my $service = Net::Google::Spreadsheet->new( auth => $oauth ); =head1 TESTING To test this module, you have to prepare as below. =over 2 =item * create a spreadsheet by hand Go to L<http://docs.google.com> and create a spreadsheet. =item * set SPREADSHEET_TITLE environment variable export SPREADSHEET_TITLE='my test spreadsheet' or so. =item * set username and password for google.com via Config::Pit install Config::Pit and type ppit set google.com then some editor comes up and type your username and password like --- username: [email protected] password: foobarbaz =item * run tests as always, perl Makefile.PL make make test =back =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::DataAPI> L<Net::OAuth> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Record> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/t/08_error.t b/t/08_error.t index a3e7c3f..1179adb 100644 --- a/t/08_error.t +++ b/t/08_error.t @@ -1,80 +1,80 @@ use strict; use Test::More; use Test::Exception; use Test::MockModule; use Test::MockObject; use LWP::UserAgent; use Net::Google::Spreadsheets; throws_ok { my $service = Net::Google::Spreadsheets->new( username => 'foo', password => 'bar', ); } qr{Net::Google::AuthSub login failed}; { my $res = Test::MockObject->new; $res->mock(is_success => sub {return 1}); my $auth = Test::MockModule->new('Net::Google::AuthSub'); $auth->mock('login' => sub {return $res}); $auth->mock(auth_params => sub {return (Authorization => 'GoogleLogin auth="foobar"')}); ok my $service = Net::Google::Spreadsheets->new( username => 'foo', password => 'bar', ); my $ua = Test::MockModule->new('LWP::UserAgent'); { $ua->mock('request' => sub { my ($self, $req) = @_; is $req->header('Authorization'), 'GoogleLogin auth="foobar"'; my $res = HTTP::Response->new(302); $res->header(Location => 'http://www.google.com/'); return $res; } ); throws_ok { $service->spreadsheets; - } qr{302 Found}; + } qr{is broken: Empty String}; } { $ua->mock('request' => sub {return HTTP::Response->parse(<<END)}); 200 OK Content-Type: application/atom+xml Content-Length: 1 1 END throws_ok { $service->spreadsheets; } qr{broken}; } { $ua->mock('request' => sub {return HTTP::Response->parse(<<END)}); 200 OK Content-Type: text/html Content-Length: 13 <html></html> END throws_ok { $service->spreadsheets; } qr{is not 'application/atom\+xml'}; } { $ua->mock('request' => sub {return HTTP::Response->parse(<<'END')}); 200 OK ETag: W/"hogehoge" Content-Type: application/atom+xml; charset=UTF-8; type=feed Content-Length: 958 <?xml version='1.0' encoding='UTF-8'?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearch/1.1/' xmlns:gd='http://schemas.google.com/g/2005' gd:etag='W/&quot;hogehoge&quot;'><id>http://spreadsheets.google.com/feeds/spreadsheets/private/full</id><updated>2009-08-15T09:41:23.289Z</updated><category scheme='http://schemas.google.com/spreadsheets/2006' term='http://schemas.google.com/spreadsheets/2006#spreadsheet'/><title>Available Spreadsheets - [email protected]</title><link rel='alternate' type='text/html' href='http://docs.google.com'/><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://spreadsheets.google.com/feeds/spreadsheets/private/full'/><link rel='self' type='application/atom+xml' href='http://spreadsheets.google.com/feeds/spreadsheets/private/full?tfe='/><openSearch:totalResults>0</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex></feed> END my @ss = $service->spreadsheets; is scalar @ss, 0; } } done_testing;
lopnor/Net-Google-Spreadsheets
4917e60622c3f841634aaa0e8559e5bf7d31ffd1
unimport things
diff --git a/Changes b/Changes index ed190c3..a5b2fc7 100644 --- a/Changes +++ b/Changes @@ -1,52 +1,55 @@ Revision history for Perl extension Net::Google::Spreadsheets +0.14 Sun Aug 15 13:15:00 2010 + - less dependencies + 0.13 Tue Aug 10 10:30:00 2010 - change default feed URL to use SSL, since Google is returning those now (thanks to dwc) 0.12 Sun Jun 07 13:00:00 2010 - fixed getting table error (thanks to sartak) - added documentations on tables, rows (thanks to siguc) - fixed num_rows property of Table was not working (thanks to Yan Wong, #57540) 0.11 Thu Apr 22 16:10:00 2010 - added documentation on deleteing items (thanks to siguc) 0.10 Mon Mar 15 23:49:00 2010 - update dependencies (Mouse 0.51, Net::Google::DataAPI 0.17) 0.09 Sun Mar 07 23:27:00 2010 - Fix spreadsheet key changes (thanks to Colin Magee) 0.08 Thu Dec 31 19:20:30 2009 - follow Net::Google::DataAPI changes - update POD 0.07 Fri Dec 22 22:53:34 2009 - now uses Net::Google::DataAPI - AuthSub and OAuth support via Net::Google::DataAPI - now uses Any::Moose 0.06 Thu Aug 20 23:21:35 2009 - Refactored internals 0.06_01 Mon Arg 16 16:01:27 2009 - Supports Google Spreadsheets API version 3.0 - Add table and record feeds supports - Better error handlings (no more redirects, captures xml parse error, and more) - Refactored internals 0.05 Sun Aug 15 09:47:50 2009 - Fix Moose attribute problem #48627 (thanks to Eric Celeste, IMALPASS) 0.04 Wed Apr 15 09:22:59 2009 - Updated POD (thanks to Mr. Grue) 0.03 Sun Apr 05 13:22:21 2009 - param method for Net::Google::Spreadsheets::Row (thanks to Mr. Grue) 0.02 Sat Apr 04 22:32:40 2009 - Crypt::SSLeay dependency - Better error message on login failure (thanks to Mr. Grue) 0.01 Tue Dec 16 23:52:25 2008 - original version diff --git a/Makefile.PL b/Makefile.PL index 194fec1..7c2fd9c 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,26 +1,26 @@ use inc::Module::Install; name 'Net-Google-Spreadsheets'; all_from 'lib/Net/Google/Spreadsheets.pm'; requires 'Carp'; requires 'XML::Atom'; requires 'Net::Google::AuthSub'; -requires 'Net::Google::DataAPI' => '0.19'; +requires 'Net::Google::DataAPI' => '0.21'; requires 'URI'; requires_any_moose( prefer => 'Mouse', moose => '0.56', mouse => '0.51', ); tests_recursive; author_tests 'xt'; build_requires 'Test::More' => '0.88'; build_requires 'Test::Exception'; build_requires 'Test::MockModule'; build_requires 'Test::MockObject'; use_test_base; auto_include; auto_set_repository; WriteAll; diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index 3f4ea68..3f7c91d 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,352 +1,353 @@ package Net::Google::Spreadsheets; use 5.008001; use Any::Moose; use Net::Google::DataAPI; use Net::Google::AuthSub; use Net::Google::DataAPI::Auth::AuthSub; our $VERSION = '0.14'; with 'Net::Google::DataAPI::Role::Service'; has gdata_version => ( is => 'ro', isa => 'Str', default => '3.0' ); has namespaces => ( is => 'ro', isa => 'HashRef', default => sub { { gs => 'http://schemas.google.com/spreadsheets/2006', gsx => 'http://schemas.google.com/spreadsheets/2006/extended', batch => 'http://schemas.google.com/gdata/batch', } }, ); has username => (is => 'ro', isa => 'Str'); has password => (is => 'ro', isa => 'Str'); has account_type => (is => 'ro', isa => 'Str', required => 1, default => 'HOSTED_OR_GOOGLE'); has source => (is => 'ro', isa => 'Str', required => 1, default => __PACKAGE__ . '-' . $VERSION); sub _build_auth { my ($self) = @_; my $authsub = Net::Google::AuthSub->new( source => $self->source, service => 'wise', account_type => $self->account_type, ); my $res = $authsub->login( $self->username, $self->password ); unless ($res && $res->is_success) { die 'Net::Google::AuthSub login failed'; } return Net::Google::DataAPI::Auth::AuthSub->new( authsub => $authsub, ); } feedurl spreadsheet => ( default => 'https://spreadsheets.google.com/feeds/spreadsheets/private/full', entry_class => 'Net::Google::Spreadsheets::Spreadsheet', can_add => 0, ); around spreadsheets => sub { my ($next, $self, $args) = @_; my @result = $next->($self, $args); if (my $key = $args->{key}) { @result = grep {$_->key eq $key} @result; } return @result; }; sub BUILD { my $self = shift; $self->auth; } __PACKAGE__->meta->make_immutable; no Any::Moose; +no Net::Google::DataAPI; 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, {row => 1, col => 4, input_value => 'age'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # fetch rows my @rows = $worksheet->rows; # or fetch rows with query @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); # delete the row $row->delete; # delete the worksheet $worksheet->delete; # create a table my $table = $spreadsheet->add_table( { worksheet => $new_worksheet, columns => ['name', 'nick', 'mail address', 'age'], } ); # add a record my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', 'mail address' => '[email protected]', age => '33', } ); # find a record my $found = $table->record( { sq => '"mail address" = "[email protected]"' } ); # delete it $found->delete; # delete table $table->delete; =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 2 =item * username Username for Google. This should be full email address format like '[email protected]'. =item * password Password corresponding to the username. =item * source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 2 =item * title title of the spreadsheet. =item * title-exact whether title search should match exactly or not. =item * key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 AUTHORIZATIONS you can optionally pass auth object argument when initializing Net::Google::Spreadsheets instance. If you want to use AuthSub mechanism, make Net::Google::DataAPI::Auth::AuthSub object and path it to the constructor: my $authsub = Net::Google::AuthSub->new; $authsub->auth(undef, $session_token); my $service = Net::Google::Spreadsheet->new( auth => $authsub ); In OAuth case, like this: my $oauth = Net::Google::DataAPI::Auth::OAuth->new( consumer_key => 'consumer.example.com', consumer_secret => 'mys3cr3t', callback => 'http://consumer.example.com/callback', ); $oauth->get_request_token; my $url = $oauth->get_authorize_token_url; # show the url to the user and get the $verifier value $oauth->get_access_token({verifier => $verifier}); my $service = Net::Google::Spreadsheet->new( auth => $oauth ); =head1 TESTING To test this module, you have to prepare as below. =over 2 =item * create a spreadsheet by hand Go to L<http://docs.google.com> and create a spreadsheet. =item * set SPREADSHEET_TITLE environment variable export SPREADSHEET_TITLE='my test spreadsheet' or so. =item * set username and password for google.com via Config::Pit install Config::Pit and type ppit set google.com then some editor comes up and type your username and password like --- username: [email protected] password: foobarbaz =item * run tests as always, perl Makefile.PL make make test =back =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::DataAPI> L<Net::OAuth> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Record> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Net/Google/Spreadsheets/Row.pm b/lib/Net/Google/Spreadsheets/Row.pm index d06fc1a..3fda427 100644 --- a/lib/Net/Google/Spreadsheets/Row.pm +++ b/lib/Net/Google/Spreadsheets/Row.pm @@ -1,172 +1,173 @@ package Net::Google::Spreadsheets::Row; use Any::Moose; use Net::Google::DataAPI; use XML::Atom::Util qw(nodelist); with 'Net::Google::DataAPI::Role::Entry', 'Net::Google::DataAPI::Role::HasContent'; after from_atom => sub { my ($self) = @_; for my $node (nodelist($self->elem, $self->ns('gsx')->{uri}, '*')) { $self->content->{$node->localname} = $node->textContent; } }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->content}) { $entry->set($self->ns('gsx'), $key, $value); } return $entry; }; __PACKAGE__->meta->make_immutable; no Any::Moose; +no Net::Google::DataAPI; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Row - A representation class for Google Spreadsheet row. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a row my $row = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->row( { sq => 'id = 1000' } ); # get the content of a row my $hashref = $row->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $row->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $row->param('name'); # returns 'Nobuo Danjou' # it's same by getting via param method without args, or content method: my $value_by_param = $row->param->{name}; my $value_by_content = $row->content->{name}; my $newval = $row->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new row value (with all fields) my $hashref2 = $row->param; # same as $row->content; # delete the row $row->delete; =head1 METHODS =head2 param sets and gets content value. =head2 delete deletes the row. =head1 CAVEATS Space characters in hash key of rows will be removed when you access rows. See below. my $ws = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'})->worksheet(1); $ws->batchupdate_cell( {col => 1,row => 1, input_value => 'name'}, {col => 2,row => 1, input_value => 'mail address'}, ); $ws->add_row( { name => 'my name', mailaddress => '[email protected]', # above passes, below fails. # 'mail address' => '[email protected]', } ); Instead, Net::Google::Spreadsheets::Table and Net::Google::Spreadsheets::Record allows space characters in column name. my $s = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'}); my $t = $s->add_table( { worksheet => $s->worksheet(1), columns => ['name', 'mail address'], } ); $t->add_record( { name => 'my name', 'mail address' => '[email protected]', } ); =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. So it's the same thing to get the value with param method or content attribute. my $value = $row->param('foo'); # it's same my $value2 = $row->content->{'foo'}; =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Spreadsheet.pm b/lib/Net/Google/Spreadsheets/Spreadsheet.pm index cf50bff..b79b0c1 100644 --- a/lib/Net/Google/Spreadsheets/Spreadsheet.pm +++ b/lib/Net/Google/Spreadsheets/Spreadsheet.pm @@ -1,251 +1,252 @@ package Net::Google::Spreadsheets::Spreadsheet; use Any::Moose; use Net::Google::DataAPI; with 'Net::Google::DataAPI::Role::Entry'; use URI; has title => ( is => 'ro', isa => 'Str', lazy_build => 1, ); entry_has key => ( isa => 'Str', is => 'ro', from_atom => sub { my ($self, $atom) = @_; my ($link) = grep { $_->rel eq 'alternate' && $_->type eq 'text/html' } $atom->link; return {URI->new($link->href)->query_form}->{key}; }, ); feedurl worksheet => ( entry_class => 'Net::Google::Spreadsheets::Worksheet', as_content_src => 1, ); feedurl table => ( entry_class => 'Net::Google::Spreadsheets::Table', rel => 'http://schemas.google.com/spreadsheets/2006#tablesfeed', ); __PACKAGE__->meta->make_immutable; no Any::Moose; +no Net::Google::DataAPI; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Spreadsheet - Representation of spreadsheet. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # create a worksheet my $worksheet = $spreadsheet->add_worksheet( { title => 'foobar', col_count => 10, row_count => 100, } ); # list worksheets my @ws = $spreadsheet->worksheets; # find a worksheet my $ws = $spreadsheet->worksheet({title => 'fooba'}); # create a table my $table = $spreadsheet->add_table( { title => 'sample table', worksheet => $worksheet, columns => ['id', 'username', 'mail', 'password'], } ); # list tables my @t = $spreadsheet->tables; # find a worksheet my $t = $spreadsheet->table({title => 'sample table'}); =head1 METHODS =head2 worksheets(\%condition) Returns a list of Net::Google::Spreadsheets::Worksheet objects. Acceptable arguments are: =over 2 =item * title =item * title-exact =back =head2 worksheet(\%condition) Returns first item of worksheets(\%condition) if available. =head2 add_worksheet(\%attribuets) Creates new worksheet and returns a Net::Google::Spreadsheets::Worksheet object representing it. Arguments (all optional) are: =over 2 =item * title =item * col_count =item * row_count =back =head2 tables(\%condition) Returns a list of Net::Google::Spreadsheets::Table objects. Acceptable arguments are: =over 2 =item * title =item * title-exact =back =head2 table(\%condition) Returns first item of tables(\%condition) if available. =head2 add_table(\%attribuets) Creates new table and returns a Net::Google::Spreadsheets::Table object representing it. Arguments are: =over 2 =item * title (optional) =item * summary (optional) =item * worksheet Worksheet where the table lives. worksheet instance or the title. =item * header (optional, default = 1) Row number of header =item * start_row (optional, default = 2) The index of the first row of the data section. =item * num_rows (optional, default = 0) Number of rows of the data section initially made. =item * insertion_mode (optional, default = 'overwrite') Insertion mode. 'insert' inserts new row into the worksheet when creating record, 'overwrite' tries to use existing rows in the worksheet. =item * columns Columns of the table. you can specify them as hashref, arrayref, arrayref of hashref. $ss->add_table( { worksheet => $ws, columns => [ {index => 1, name => 'foo'}, {index => 2, name => 'bar'}, {index => 3, name => 'baz'}, ], } ); $ss->add_table( { worksheet => $ws, columns => { A => 'foo', B => 'bar', C => 'baz', } } ); $ss->add_table( { worksheet => $ws, columns => ['foo', 'bar', 'baz'], } ); 'index' of the first case and hash key of the second case is column index of the worksheet. In the third case, the columns is automatically placed to the columns of the worksheet from 'A' to 'Z' order. =back =head1 DELETING A SPREADSHEET To delete a spreadsheet, use L<Net::Google::DocumentsList>. my $docs = Net::Google::DocumentsList->new( username => '[email protected]', password => 'mypassword' ); $docs->item({resource_id => 'spreadsheet:'. $ss->key})->delete; =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Table> L<Net::Google::DocumentsList> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut
lopnor/Net-Google-Spreadsheets
062a3884bb8650f9dbedb83bbe52dc10e0ba24fd
less dependency
diff --git a/Makefile.PL b/Makefile.PL index d8fba05..194fec1 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,27 +1,26 @@ use inc::Module::Install; name 'Net-Google-Spreadsheets'; all_from 'lib/Net/Google/Spreadsheets.pm'; requires 'Carp'; requires 'XML::Atom'; requires 'Net::Google::AuthSub'; requires 'Net::Google::DataAPI' => '0.19'; requires 'URI'; -requires 'namespace::autoclean'; requires_any_moose( prefer => 'Mouse', moose => '0.56', mouse => '0.51', ); tests_recursive; author_tests 'xt'; build_requires 'Test::More' => '0.88'; build_requires 'Test::Exception'; build_requires 'Test::MockModule'; build_requires 'Test::MockObject'; use_test_base; auto_include; auto_set_repository; WriteAll; diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index cfbe488..3f4ea68 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,352 +1,352 @@ package Net::Google::Spreadsheets; use 5.008001; use Any::Moose; use Net::Google::DataAPI; use Net::Google::AuthSub; use Net::Google::DataAPI::Auth::AuthSub; -our $VERSION = '0.13'; +our $VERSION = '0.14'; with 'Net::Google::DataAPI::Role::Service'; has gdata_version => ( is => 'ro', isa => 'Str', default => '3.0' ); has namespaces => ( is => 'ro', isa => 'HashRef', default => sub { { gs => 'http://schemas.google.com/spreadsheets/2006', gsx => 'http://schemas.google.com/spreadsheets/2006/extended', batch => 'http://schemas.google.com/gdata/batch', } }, ); has username => (is => 'ro', isa => 'Str'); has password => (is => 'ro', isa => 'Str'); has account_type => (is => 'ro', isa => 'Str', required => 1, default => 'HOSTED_OR_GOOGLE'); has source => (is => 'ro', isa => 'Str', required => 1, default => __PACKAGE__ . '-' . $VERSION); sub _build_auth { my ($self) = @_; my $authsub = Net::Google::AuthSub->new( source => $self->source, service => 'wise', account_type => $self->account_type, ); my $res = $authsub->login( $self->username, $self->password ); unless ($res && $res->is_success) { die 'Net::Google::AuthSub login failed'; } return Net::Google::DataAPI::Auth::AuthSub->new( authsub => $authsub, ); } feedurl spreadsheet => ( default => 'https://spreadsheets.google.com/feeds/spreadsheets/private/full', entry_class => 'Net::Google::Spreadsheets::Spreadsheet', can_add => 0, ); around spreadsheets => sub { my ($next, $self, $args) = @_; my @result = $next->($self, $args); if (my $key = $args->{key}) { @result = grep {$_->key eq $key} @result; } return @result; }; sub BUILD { my $self = shift; $self->auth; } __PACKAGE__->meta->make_immutable; no Any::Moose; 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, {row => 1, col => 4, input_value => 'age'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # fetch rows my @rows = $worksheet->rows; # or fetch rows with query @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); # delete the row $row->delete; # delete the worksheet $worksheet->delete; # create a table my $table = $spreadsheet->add_table( { worksheet => $new_worksheet, columns => ['name', 'nick', 'mail address', 'age'], } ); # add a record my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', 'mail address' => '[email protected]', age => '33', } ); # find a record my $found = $table->record( { sq => '"mail address" = "[email protected]"' } ); # delete it $found->delete; # delete table $table->delete; =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 2 =item * username Username for Google. This should be full email address format like '[email protected]'. =item * password Password corresponding to the username. =item * source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 2 =item * title title of the spreadsheet. =item * title-exact whether title search should match exactly or not. =item * key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 AUTHORIZATIONS you can optionally pass auth object argument when initializing Net::Google::Spreadsheets instance. If you want to use AuthSub mechanism, make Net::Google::DataAPI::Auth::AuthSub object and path it to the constructor: my $authsub = Net::Google::AuthSub->new; $authsub->auth(undef, $session_token); my $service = Net::Google::Spreadsheet->new( auth => $authsub ); In OAuth case, like this: my $oauth = Net::Google::DataAPI::Auth::OAuth->new( consumer_key => 'consumer.example.com', consumer_secret => 'mys3cr3t', callback => 'http://consumer.example.com/callback', ); $oauth->get_request_token; my $url = $oauth->get_authorize_token_url; # show the url to the user and get the $verifier value $oauth->get_access_token({verifier => $verifier}); my $service = Net::Google::Spreadsheet->new( auth => $oauth ); =head1 TESTING To test this module, you have to prepare as below. =over 2 =item * create a spreadsheet by hand Go to L<http://docs.google.com> and create a spreadsheet. =item * set SPREADSHEET_TITLE environment variable export SPREADSHEET_TITLE='my test spreadsheet' or so. =item * set username and password for google.com via Config::Pit install Config::Pit and type ppit set google.com then some editor comes up and type your username and password like --- username: [email protected] password: foobarbaz =item * run tests as always, perl Makefile.PL make make test =back =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::DataAPI> L<Net::OAuth> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Record> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
lopnor/Net-Google-Spreadsheets
6c1d26bad76f67af707bba41017e255eee3ba2eb
less dependency
diff --git a/Makefile.PL b/Makefile.PL index d0c1322..d8fba05 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,26 +1,27 @@ use inc::Module::Install; name 'Net-Google-Spreadsheets'; all_from 'lib/Net/Google/Spreadsheets.pm'; requires 'Carp'; requires 'XML::Atom'; requires 'Net::Google::AuthSub'; requires 'Net::Google::DataAPI' => '0.19'; requires 'URI'; requires 'namespace::autoclean'; requires_any_moose( + prefer => 'Mouse', moose => '0.56', mouse => '0.51', ); tests_recursive; author_tests 'xt'; build_requires 'Test::More' => '0.88'; build_requires 'Test::Exception'; build_requires 'Test::MockModule'; build_requires 'Test::MockObject'; use_test_base; auto_include; auto_set_repository; WriteAll; diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index 316491b..cfbe488 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,351 +1,352 @@ package Net::Google::Spreadsheets; +use 5.008001; use Any::Moose; use Net::Google::DataAPI; -use namespace::autoclean; -use 5.008001; use Net::Google::AuthSub; use Net::Google::DataAPI::Auth::AuthSub; our $VERSION = '0.13'; with 'Net::Google::DataAPI::Role::Service'; has gdata_version => ( is => 'ro', isa => 'Str', default => '3.0' ); has namespaces => ( is => 'ro', isa => 'HashRef', default => sub { { gs => 'http://schemas.google.com/spreadsheets/2006', gsx => 'http://schemas.google.com/spreadsheets/2006/extended', batch => 'http://schemas.google.com/gdata/batch', } }, ); has username => (is => 'ro', isa => 'Str'); has password => (is => 'ro', isa => 'Str'); has account_type => (is => 'ro', isa => 'Str', required => 1, default => 'HOSTED_OR_GOOGLE'); has source => (is => 'ro', isa => 'Str', required => 1, default => __PACKAGE__ . '-' . $VERSION); sub _build_auth { my ($self) = @_; my $authsub = Net::Google::AuthSub->new( source => $self->source, service => 'wise', account_type => $self->account_type, ); my $res = $authsub->login( $self->username, $self->password ); unless ($res && $res->is_success) { die 'Net::Google::AuthSub login failed'; } return Net::Google::DataAPI::Auth::AuthSub->new( authsub => $authsub, ); } feedurl spreadsheet => ( default => 'https://spreadsheets.google.com/feeds/spreadsheets/private/full', entry_class => 'Net::Google::Spreadsheets::Spreadsheet', can_add => 0, ); around spreadsheets => sub { my ($next, $self, $args) = @_; my @result = $next->($self, $args); if (my $key = $args->{key}) { @result = grep {$_->key eq $key} @result; } return @result; }; sub BUILD { my $self = shift; $self->auth; } __PACKAGE__->meta->make_immutable; +no Any::Moose; + 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, {row => 1, col => 4, input_value => 'age'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # fetch rows my @rows = $worksheet->rows; # or fetch rows with query @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); # delete the row $row->delete; # delete the worksheet $worksheet->delete; # create a table my $table = $spreadsheet->add_table( { worksheet => $new_worksheet, columns => ['name', 'nick', 'mail address', 'age'], } ); # add a record my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', 'mail address' => '[email protected]', age => '33', } ); # find a record my $found = $table->record( { sq => '"mail address" = "[email protected]"' } ); # delete it $found->delete; # delete table $table->delete; =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 2 =item * username Username for Google. This should be full email address format like '[email protected]'. =item * password Password corresponding to the username. =item * source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 2 =item * title title of the spreadsheet. =item * title-exact whether title search should match exactly or not. =item * key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 AUTHORIZATIONS you can optionally pass auth object argument when initializing Net::Google::Spreadsheets instance. If you want to use AuthSub mechanism, make Net::Google::DataAPI::Auth::AuthSub object and path it to the constructor: my $authsub = Net::Google::AuthSub->new; $authsub->auth(undef, $session_token); my $service = Net::Google::Spreadsheet->new( auth => $authsub ); In OAuth case, like this: my $oauth = Net::Google::DataAPI::Auth::OAuth->new( consumer_key => 'consumer.example.com', consumer_secret => 'mys3cr3t', callback => 'http://consumer.example.com/callback', ); $oauth->get_request_token; my $url = $oauth->get_authorize_token_url; # show the url to the user and get the $verifier value $oauth->get_access_token({verifier => $verifier}); my $service = Net::Google::Spreadsheet->new( auth => $oauth ); =head1 TESTING To test this module, you have to prepare as below. =over 2 =item * create a spreadsheet by hand Go to L<http://docs.google.com> and create a spreadsheet. =item * set SPREADSHEET_TITLE environment variable export SPREADSHEET_TITLE='my test spreadsheet' or so. =item * set username and password for google.com via Config::Pit install Config::Pit and type ppit set google.com then some editor comes up and type your username and password like --- username: [email protected] password: foobarbaz =item * run tests as always, perl Makefile.PL make make test =back =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::DataAPI> L<Net::OAuth> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Record> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Net/Google/Spreadsheets/Cell.pm b/lib/Net/Google/Spreadsheets/Cell.pm index 52f111c..1b05a50 100644 --- a/lib/Net/Google/Spreadsheets/Cell.pm +++ b/lib/Net/Google/Spreadsheets/Cell.pm @@ -1,122 +1,123 @@ package Net::Google::Spreadsheets::Cell; use Any::Moose; -use namespace::autoclean; use XML::Atom::Util qw(first); with 'Net::Google::DataAPI::Role::Entry'; has content => ( isa => 'Str', is => 'ro', ); has row => ( isa => 'Int', is => 'ro', ); has col => ( isa => 'Int', is => 'ro', ); has input_value => ( isa => 'Str', is => 'rw', trigger => sub {$_[0]->update}, ); after from_atom => sub { my ($self) = @_; my $elem = first( $self->elem, $self->ns('gs')->{uri}, 'cell'); $self->{row} = $elem->getAttribute('row'); $self->{col} = $elem->getAttribute('col'); $self->{input_value} = $elem->getAttribute('inputValue'); $self->{content} = $elem->textContent || ''; }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->ns('gs'), 'cell', '', { row => $self->row, col => $self->col, inputValue => $self->input_value, } ); my $link = XML::Atom::Link->new; $link->rel('edit'); $link->type('application/atom+xml'); $link->href($self->editurl); $entry->link($link); $entry->id($self->id); return $entry; }; __PACKAGE__->meta->make_immutable; +no Any::Moose; + 1; __END__ =head1 NAME Net::Google::Spreadsheets::Cell - A representation class for Google Spreadsheet cell. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a cell my $cell = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->cell( { col => 1, row => 1, } ); # update a cell $cell->input_value('new value'); # get the content of a cell my $value = $cell->content; =head1 ATTRIBUTES =head2 input_value Rewritable attribute. You can set formula like '=A1+B1' or so. =head2 content Read only attribute. You can get the result of formula. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Record.pm b/lib/Net/Google/Spreadsheets/Record.pm index d45f23f..e7b75b6 100644 --- a/lib/Net/Google/Spreadsheets/Record.pm +++ b/lib/Net/Google/Spreadsheets/Record.pm @@ -1,136 +1,137 @@ package Net::Google::Spreadsheets::Record; use Any::Moose; -use namespace::autoclean; use XML::Atom::Util qw(nodelist); with 'Net::Google::DataAPI::Role::Entry', 'Net::Google::DataAPI::Role::HasContent'; after from_atom => sub { my ($self) = @_; for my $node (nodelist($self->elem, $self->ns('gs')->{uri}, 'field')) { $self->content->{$node->getAttribute('name')} = $node->textContent; } }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->content}) { $entry->add($self->ns('gs'), 'field', $value, {name => $key}); } return $entry; }; __PACKAGE__->meta->make_immutable; +no Any::Moose; + 1; __END__ =head1 NAME Net::Google::Spreadsheets::Record - A representation class for Google Spreadsheet record. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a record my $record = $service->spreadsheet( { title => 'list for new year cards', } )->table( { title => 'addressbook', } )->record( { sq => 'id = 1000', } ); # get the content of a row my $hashref = $record->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $record->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $record->param('name'); # returns 'Nobuo Danjou' # you can also get it via content like this: my $value_via_content = $record->content->{name}; my $newval = $record->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new record value (with all fields) my $hashref2 = $record->param; # same as $record->content; # setting whole new content $record->content( { id => 8080, address => 'nowhere', zip => '999-9999', name => 'nowhere man' } ); # delete a record $record->delete; =head1 METHODS =head2 param sets and gets content value. =head2 delete deletes the record. =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Row> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Row.pm b/lib/Net/Google/Spreadsheets/Row.pm index 804d3d3..d06fc1a 100644 --- a/lib/Net/Google/Spreadsheets/Row.pm +++ b/lib/Net/Google/Spreadsheets/Row.pm @@ -1,171 +1,172 @@ package Net::Google::Spreadsheets::Row; use Any::Moose; -use namespace::autoclean; use Net::Google::DataAPI; use XML::Atom::Util qw(nodelist); with 'Net::Google::DataAPI::Role::Entry', 'Net::Google::DataAPI::Role::HasContent'; after from_atom => sub { my ($self) = @_; for my $node (nodelist($self->elem, $self->ns('gsx')->{uri}, '*')) { $self->content->{$node->localname} = $node->textContent; } }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->content}) { $entry->set($self->ns('gsx'), $key, $value); } return $entry; }; __PACKAGE__->meta->make_immutable; +no Any::Moose; + 1; __END__ =head1 NAME Net::Google::Spreadsheets::Row - A representation class for Google Spreadsheet row. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a row my $row = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->row( { sq => 'id = 1000' } ); # get the content of a row my $hashref = $row->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $row->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $row->param('name'); # returns 'Nobuo Danjou' # it's same by getting via param method without args, or content method: my $value_by_param = $row->param->{name}; my $value_by_content = $row->content->{name}; my $newval = $row->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new row value (with all fields) my $hashref2 = $row->param; # same as $row->content; # delete the row $row->delete; =head1 METHODS =head2 param sets and gets content value. =head2 delete deletes the row. =head1 CAVEATS Space characters in hash key of rows will be removed when you access rows. See below. my $ws = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'})->worksheet(1); $ws->batchupdate_cell( {col => 1,row => 1, input_value => 'name'}, {col => 2,row => 1, input_value => 'mail address'}, ); $ws->add_row( { name => 'my name', mailaddress => '[email protected]', # above passes, below fails. # 'mail address' => '[email protected]', } ); Instead, Net::Google::Spreadsheets::Table and Net::Google::Spreadsheets::Record allows space characters in column name. my $s = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'}); my $t = $s->add_table( { worksheet => $s->worksheet(1), columns => ['name', 'mail address'], } ); $t->add_record( { name => 'my name', 'mail address' => '[email protected]', } ); =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. So it's the same thing to get the value with param method or content attribute. my $value = $row->param('foo'); # it's same my $value2 = $row->content->{'foo'}; =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Spreadsheet.pm b/lib/Net/Google/Spreadsheets/Spreadsheet.pm index 1f4bb27..cf50bff 100644 --- a/lib/Net/Google/Spreadsheets/Spreadsheet.pm +++ b/lib/Net/Google/Spreadsheets/Spreadsheet.pm @@ -1,250 +1,251 @@ package Net::Google::Spreadsheets::Spreadsheet; use Any::Moose; -use namespace::autoclean; use Net::Google::DataAPI; with 'Net::Google::DataAPI::Role::Entry'; use URI; has title => ( is => 'ro', isa => 'Str', lazy_build => 1, ); entry_has key => ( isa => 'Str', is => 'ro', from_atom => sub { my ($self, $atom) = @_; my ($link) = grep { $_->rel eq 'alternate' && $_->type eq 'text/html' } $atom->link; return {URI->new($link->href)->query_form}->{key}; }, ); feedurl worksheet => ( entry_class => 'Net::Google::Spreadsheets::Worksheet', as_content_src => 1, ); feedurl table => ( entry_class => 'Net::Google::Spreadsheets::Table', rel => 'http://schemas.google.com/spreadsheets/2006#tablesfeed', ); __PACKAGE__->meta->make_immutable; +no Any::Moose; + 1; __END__ =head1 NAME Net::Google::Spreadsheets::Spreadsheet - Representation of spreadsheet. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # create a worksheet my $worksheet = $spreadsheet->add_worksheet( { title => 'foobar', col_count => 10, row_count => 100, } ); # list worksheets my @ws = $spreadsheet->worksheets; # find a worksheet my $ws = $spreadsheet->worksheet({title => 'fooba'}); # create a table my $table = $spreadsheet->add_table( { title => 'sample table', worksheet => $worksheet, columns => ['id', 'username', 'mail', 'password'], } ); # list tables my @t = $spreadsheet->tables; # find a worksheet my $t = $spreadsheet->table({title => 'sample table'}); =head1 METHODS =head2 worksheets(\%condition) Returns a list of Net::Google::Spreadsheets::Worksheet objects. Acceptable arguments are: =over 2 =item * title =item * title-exact =back =head2 worksheet(\%condition) Returns first item of worksheets(\%condition) if available. =head2 add_worksheet(\%attribuets) Creates new worksheet and returns a Net::Google::Spreadsheets::Worksheet object representing it. Arguments (all optional) are: =over 2 =item * title =item * col_count =item * row_count =back =head2 tables(\%condition) Returns a list of Net::Google::Spreadsheets::Table objects. Acceptable arguments are: =over 2 =item * title =item * title-exact =back =head2 table(\%condition) Returns first item of tables(\%condition) if available. =head2 add_table(\%attribuets) Creates new table and returns a Net::Google::Spreadsheets::Table object representing it. Arguments are: =over 2 =item * title (optional) =item * summary (optional) =item * worksheet Worksheet where the table lives. worksheet instance or the title. =item * header (optional, default = 1) Row number of header =item * start_row (optional, default = 2) The index of the first row of the data section. =item * num_rows (optional, default = 0) Number of rows of the data section initially made. =item * insertion_mode (optional, default = 'overwrite') Insertion mode. 'insert' inserts new row into the worksheet when creating record, 'overwrite' tries to use existing rows in the worksheet. =item * columns Columns of the table. you can specify them as hashref, arrayref, arrayref of hashref. $ss->add_table( { worksheet => $ws, columns => [ {index => 1, name => 'foo'}, {index => 2, name => 'bar'}, {index => 3, name => 'baz'}, ], } ); $ss->add_table( { worksheet => $ws, columns => { A => 'foo', B => 'bar', C => 'baz', } } ); $ss->add_table( { worksheet => $ws, columns => ['foo', 'bar', 'baz'], } ); 'index' of the first case and hash key of the second case is column index of the worksheet. In the third case, the columns is automatically placed to the columns of the worksheet from 'A' to 'Z' order. =back =head1 DELETING A SPREADSHEET To delete a spreadsheet, use L<Net::Google::DocumentsList>. my $docs = Net::Google::DocumentsList->new( username => '[email protected]', password => 'mypassword' ); $docs->item({resource_id => 'spreadsheet:'. $ss->key})->delete; =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Table> L<Net::Google::DocumentsList> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Table.pm b/lib/Net/Google/Spreadsheets/Table.pm index 683d3b4..78aba39 100644 --- a/lib/Net/Google/Spreadsheets/Table.pm +++ b/lib/Net/Google/Spreadsheets/Table.pm @@ -1,236 +1,241 @@ package Net::Google::Spreadsheets::Table; use Any::Moose; use Any::Moose '::Util::TypeConstraints'; -use namespace::autoclean; use Net::Google::DataAPI; use XML::Atom::Util qw(nodelist first create_element); use Net::Google::Spreadsheets::Worksheet; use Net::Google::Spreadsheets::Record; with 'Net::Google::DataAPI::Role::Entry'; subtype 'ColumnList' => as 'ArrayRef[Net::Google::Spreadsheets::Table::Column]'; coerce 'ColumnList' => from 'ArrayRef[HashRef]' => via { [ map {Net::Google::Spreadsheets::Table::Column->new($_)} @$_ ] }; coerce 'ColumnList' => from 'ArrayRef[Str]' => via { my @c; my $index = 0; for my $value (@$_) { push @c, Net::Google::Spreadsheets::Table::Column->new( index => ++$index, name => $value, ); } \@c; }; coerce 'ColumnList' => from 'HashRef' => via { my @c; while (my ($key, $value) = each(%$_)) { push @c, Net::Google::Spreadsheets::Table::Column->new( index => $key, name => $value, ); } \@c; }; subtype 'WorksheetName' => as 'Str'; coerce 'WorksheetName' => from 'Net::Google::Spreadsheets::Worksheet' => via { $_->title }; feedurl record => ( entry_class => 'Net::Google::Spreadsheets::Record', arg_builder => sub { my ($self, $args) = @_; return {content => $args}; }, as_content_src => 1, ); has summary => ( is => 'rw', isa => 'Str' ); has worksheet => ( is => 'ro', isa => 'WorksheetName', coerce => 1 ); has header => ( is => 'ro', isa => 'Int', required => 1, default => 1 ); has start_row => ( is => 'ro', isa => 'Int', required => 1, default => 2 ); has num_rows => ( is => 'ro', isa => 'Int' ); has columns => ( is => 'ro', isa => 'ColumnList', coerce => 1 ); has insertion_mode => ( is => 'ro', isa => (enum ['insert', 'overwrite']), default => 'overwrite' ); after from_atom => sub { my ($self) = @_; my $gsns = $self->ns('gs')->{uri}; my $elem = $self->elem; $self->{summary} = $self->atom->summary; $self->{worksheet} = first( $elem, $gsns, 'worksheet')->getAttribute('name'); $self->{header} = first( $elem, $gsns, 'header')->getAttribute('row'); my @columns; my $data = first($elem, $gsns, 'data'); $self->{insertion_mode} = $data->getAttribute('insertionMode'); $self->{start_row} = $data->getAttribute('startRow'); $self->{num_rows} = $data->getAttribute('numRows'); for (nodelist($data, $gsns, 'column')) { push @columns, Net::Google::Spreadsheets::Table::Column->new( index => $_->getAttribute('index'), name => $_->getAttribute('name'), ); } $self->{columns} = \@columns; }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); my $gsns = $self->ns('gs')->{uri}; $entry->summary($self->summary) if $self->summary; $entry->set($gsns, 'worksheet', '', {name => $self->worksheet}); $entry->set($gsns, 'header', '', {row => $self->header}); my $data = create_element($gsns, 'data'); $data->setAttribute(startRow => $self->start_row); $data->setAttribute(insertionMode => $self->insertion_mode); $data->setAttribute(numRows => $self->num_rows) if $self->num_rows; for ( @{$self->columns} ) { my $column = create_element($gsns, 'column'); $column->setAttribute(index => $_->index); $column->setAttribute(name => $_->name); $data->appendChild($column); } $entry->set($gsns, 'data', $data); return $entry; }; __PACKAGE__->meta->make_immutable; +no Any::Moose; +no Any::Moose '::Util::TypeConstraints'; +no Net::Google::DataAPI; + package # hide from PAUSE Net::Google::Spreadsheets::Table::Column; use Any::Moose; has 'index' => ( is => 'ro', isa => 'Str' ); has 'name' => ( is => 'ro', isa => 'Str' ); __PACKAGE__->meta->make_immutable; +no Any::Moose; + 1; __END__ =head1 NAME Net::Google::Spreadsheets::Table - A representation class for Google Spreadsheet table. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a table my $table = $service->spreadsheet( { title => 'list for new year cards', } )->table( { title => 'sample table', } ); # create a record my $r = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # get records my @records = $table->records; # search records @records = $table->records({sq => 'age > 20'}); # search a record my $record = $table->record({sq => 'name = "Nobuo Danjou"'}); =head1 METHODS =head2 records(\%condition) Returns a list of Net::Google::Spreadsheets::Record objects. Acceptable arguments are: =over 2 =item * sq Structured query on the full text in the worksheet. see the URL below for detail. =item * orderby Set column name to use for ordering. =item * reverse Set 'true' or 'false'. The default is 'false'. It reverses the order. =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#RecordParameters> for details. =head2 record(\%condition) Returns first item of records(\%condition) if available. =head2 add_record(\%contents) Creates new record and returns a Net::Google::Spreadsheets::Record object representing it. Arguments are contents of a row as a hashref. my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); =head1 CAVEATS You can access to the table structure and records only from the Google Spreadsheets API. It means you can't create tables, add records or delete tables via web interface. It will make some problems if you want to access the data both from API and web interface. In that case, you should use $worksheets->row(s) methods instead. See the documents below for details: L<http://code.google.com/intl/en/apis/spreadsheets/data/3.0/developers_guide_protocol.html#TableFeeds> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Record> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Worksheet.pm b/lib/Net/Google/Spreadsheets/Worksheet.pm index 8c54f1b..e6afba6 100644 --- a/lib/Net/Google/Spreadsheets/Worksheet.pm +++ b/lib/Net/Google/Spreadsheets/Worksheet.pm @@ -1,258 +1,260 @@ package Net::Google::Spreadsheets::Worksheet; use Any::Moose; -use namespace::autoclean; use Net::Google::DataAPI; with 'Net::Google::DataAPI::Role::Entry'; use Carp; use Net::Google::Spreadsheets::Cell; use XML::Atom::Util qw(first); feedurl row => ( entry_class => 'Net::Google::Spreadsheets::Row', as_content_src => 1, arg_builder => sub { my ($self, $args) = @_; return {content => $args}; }, ); feedurl cell => ( entry_class => 'Net::Google::Spreadsheets::Cell', can_add => 0, rel => 'http://schemas.google.com/spreadsheets/2006#cellsfeed', query_builder => sub { my ($self, $args) = @_; if (my $col = delete $args->{col}) { $args->{'max-col'} = $col; $args->{'min-col'} = $col; $args->{'return-empty'} = 'true'; } if (my $row = delete $args->{row}) { $args->{'max-row'} = $row; $args->{'min-row'} = $row; $args->{'return-empty'} = 'true'; } return $args; }, ); entry_has row_count => ( isa => 'Int', is => 'rw', default => 100, tagname => 'rowCount', ns => 'gs', ); entry_has col_count => ( isa => 'Int', is => 'rw', default => 20, tagname => 'colCount', ns => 'gs', ); __PACKAGE__->meta->make_immutable; sub batchupdate_cell { my ($self, @args) = @_; my $feed = XML::Atom::Feed->new; for ( @args ) { my $id = sprintf("%s/R%sC%s",$self->cell_feedurl, $_->{row}, $_->{col}); $_->{id} = $_->{editurl} = $id; $_->{container} = $self, my $entry = Net::Google::Spreadsheets::Cell->new($_)->to_atom; $entry->set($self->ns('batch'), operation => '', {type => 'update'}); $entry->set($self->ns('batch'), id => $id); $feed->add_entry($entry); } my $res_feed = $self->service->post( $self->cell_feedurl."/batch", $feed, {'If-Match' => '*'} ); $self->sync; return map { Net::Google::Spreadsheets::Cell->new( atom => $_, container => $self, ) } grep { my $node = first( $_->elem, $self->ns('batch')->{uri}, 'status' ); $node->getAttribute('code') == 200; } $res_feed->entries; } +no Any::Moose; +no Net::Google::DataAPI; + 1; __END__ =head1 NAME Net::Google::Spreadsheets::Worksheet - Representation of worksheet. =head1 SYNOPSIS my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); my $ss = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); my $worksheet = $ss->worksheet({title => 'Sheet1'}); # update cell by batch request $worksheet->batchupdate_cell( {col => 1, row => 1, input_value => 'name'}, {col => 2, row => 1, input_value => 'nick'}, {col => 3, row => 1, input_value => 'mail'}, {col => 4, row => 1, input_value => 'age'}, ); # get a cell object my $cell = $worksheet->cell({col => 1, row => 1}); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # get rows my @rows = $worksheet->rows; # search rows @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # delete the worksheet # Note that this will fail if the worksheet is the only one # within the spreadsheet. $worksheet->delete; =head1 METHODS =head2 rows(\%condition) Returns a list of Net::Google::Spreadsheets::Row objects. Acceptable arguments are: =over 2 =item * sq Structured query on the full text in the worksheet. see the URL below for detail. =item * orderby Set column name to use for ordering. =item * reverse Set 'true' or 'false'. The default is 'false'. =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#ListParameters> for details. Note that 'the first row of the worksheet' you can see with the browser is 'header' for the rows, so you can't get it with this method. Use cell(s) method instead if you need to access them. =head2 row(\%condition) Returns first item of rows(\%condition) if available. =head2 add_row(\%contents) Creates new row and returns a Net::Google::Spreadsheets::Row object representing it. Arguments are contents of a row as a hashref. my $row = $ws->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); =head2 cells(\%args) Returns a list of Net::Google::Spreadsheets::Cell objects. Acceptable arguments are: =over 2 =item * min-row =item * max-row =item * min-col =item * max-col =item * range =item * return-empty =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#CellParameters> for details. =head2 cell(\%args) Returns Net::Google::Spreadsheets::Cell object. Arguments are: =over 2 =item * col =item * row =back =head2 batchupdate_cell(@args) update multiple cells with a batch request. Pass a list of hash references containing: =over 2 =item * col =item * row =item * input_value =back =head2 delete Deletes the worksheet. Note that this will fail if the worksheet is only one within the spreadsheet. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut
lopnor/Net-Google-Spreadsheets
d18a08147888b92d9ae20a34a4ed4e00f249c4c7
Checking in changes prior to tagging of version 0.13.
diff --git a/Changes b/Changes index 28b36cf..ed190c3 100644 --- a/Changes +++ b/Changes @@ -1,51 +1,52 @@ Revision history for Perl extension Net::Google::Spreadsheets - - change default feed URL to use SSL, since Google is returning those now +0.13 Tue Aug 10 10:30:00 2010 + - change default feed URL to use SSL, since Google is returning those now (thanks to dwc) -0.12 Sun Jul 07 13:00:00 2010 +0.12 Sun Jun 07 13:00:00 2010 - fixed getting table error (thanks to sartak) - added documentations on tables, rows (thanks to siguc) - fixed num_rows property of Table was not working (thanks to Yan Wong, #57540) 0.11 Thu Apr 22 16:10:00 2010 - added documentation on deleteing items (thanks to siguc) 0.10 Mon Mar 15 23:49:00 2010 - update dependencies (Mouse 0.51, Net::Google::DataAPI 0.17) 0.09 Sun Mar 07 23:27:00 2010 - Fix spreadsheet key changes (thanks to Colin Magee) 0.08 Thu Dec 31 19:20:30 2009 - follow Net::Google::DataAPI changes - update POD 0.07 Fri Dec 22 22:53:34 2009 - now uses Net::Google::DataAPI - AuthSub and OAuth support via Net::Google::DataAPI - now uses Any::Moose 0.06 Thu Aug 20 23:21:35 2009 - Refactored internals 0.06_01 Mon Arg 16 16:01:27 2009 - Supports Google Spreadsheets API version 3.0 - Add table and record feeds supports - Better error handlings (no more redirects, captures xml parse error, and more) - Refactored internals 0.05 Sun Aug 15 09:47:50 2009 - Fix Moose attribute problem #48627 (thanks to Eric Celeste, IMALPASS) 0.04 Wed Apr 15 09:22:59 2009 - Updated POD (thanks to Mr. Grue) 0.03 Sun Apr 05 13:22:21 2009 - param method for Net::Google::Spreadsheets::Row (thanks to Mr. Grue) 0.02 Sat Apr 04 22:32:40 2009 - Crypt::SSLeay dependency - Better error message on login failure (thanks to Mr. Grue) 0.01 Tue Dec 16 23:52:25 2008 - original version diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index d42c617..316491b 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,351 +1,351 @@ package Net::Google::Spreadsheets; use Any::Moose; use Net::Google::DataAPI; use namespace::autoclean; use 5.008001; use Net::Google::AuthSub; use Net::Google::DataAPI::Auth::AuthSub; -our $VERSION = '0.12'; +our $VERSION = '0.13'; with 'Net::Google::DataAPI::Role::Service'; has gdata_version => ( is => 'ro', isa => 'Str', default => '3.0' ); has namespaces => ( is => 'ro', isa => 'HashRef', default => sub { { gs => 'http://schemas.google.com/spreadsheets/2006', gsx => 'http://schemas.google.com/spreadsheets/2006/extended', batch => 'http://schemas.google.com/gdata/batch', } }, ); has username => (is => 'ro', isa => 'Str'); has password => (is => 'ro', isa => 'Str'); has account_type => (is => 'ro', isa => 'Str', required => 1, default => 'HOSTED_OR_GOOGLE'); has source => (is => 'ro', isa => 'Str', required => 1, default => __PACKAGE__ . '-' . $VERSION); sub _build_auth { my ($self) = @_; my $authsub = Net::Google::AuthSub->new( source => $self->source, service => 'wise', account_type => $self->account_type, ); my $res = $authsub->login( $self->username, $self->password ); unless ($res && $res->is_success) { die 'Net::Google::AuthSub login failed'; } return Net::Google::DataAPI::Auth::AuthSub->new( authsub => $authsub, ); } feedurl spreadsheet => ( default => 'https://spreadsheets.google.com/feeds/spreadsheets/private/full', entry_class => 'Net::Google::Spreadsheets::Spreadsheet', can_add => 0, ); around spreadsheets => sub { my ($next, $self, $args) = @_; my @result = $next->($self, $args); if (my $key = $args->{key}) { @result = grep {$_->key eq $key} @result; } return @result; }; sub BUILD { my $self = shift; $self->auth; } __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, {row => 1, col => 4, input_value => 'age'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # fetch rows my @rows = $worksheet->rows; # or fetch rows with query @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); # delete the row $row->delete; # delete the worksheet $worksheet->delete; # create a table my $table = $spreadsheet->add_table( { worksheet => $new_worksheet, columns => ['name', 'nick', 'mail address', 'age'], } ); # add a record my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', 'mail address' => '[email protected]', age => '33', } ); # find a record my $found = $table->record( { sq => '"mail address" = "[email protected]"' } ); # delete it $found->delete; # delete table $table->delete; =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 2 =item * username Username for Google. This should be full email address format like '[email protected]'. =item * password Password corresponding to the username. =item * source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 2 =item * title title of the spreadsheet. =item * title-exact whether title search should match exactly or not. =item * key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 AUTHORIZATIONS you can optionally pass auth object argument when initializing Net::Google::Spreadsheets instance. If you want to use AuthSub mechanism, make Net::Google::DataAPI::Auth::AuthSub object and path it to the constructor: my $authsub = Net::Google::AuthSub->new; $authsub->auth(undef, $session_token); my $service = Net::Google::Spreadsheet->new( auth => $authsub ); In OAuth case, like this: my $oauth = Net::Google::DataAPI::Auth::OAuth->new( consumer_key => 'consumer.example.com', consumer_secret => 'mys3cr3t', callback => 'http://consumer.example.com/callback', ); $oauth->get_request_token; my $url = $oauth->get_authorize_token_url; # show the url to the user and get the $verifier value $oauth->get_access_token({verifier => $verifier}); my $service = Net::Google::Spreadsheet->new( auth => $oauth ); =head1 TESTING To test this module, you have to prepare as below. =over 2 =item * create a spreadsheet by hand Go to L<http://docs.google.com> and create a spreadsheet. =item * set SPREADSHEET_TITLE environment variable export SPREADSHEET_TITLE='my test spreadsheet' or so. =item * set username and password for google.com via Config::Pit install Config::Pit and type ppit set google.com then some editor comes up and type your username and password like --- username: [email protected] password: foobarbaz =item * run tests as always, perl Makefile.PL make make test =back =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::DataAPI> L<Net::OAuth> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Record> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
lopnor/Net-Google-Spreadsheets
accf5e8606f9ee3fb0db16f3ebb42954d52057cc
Change default feed URL to use SSL, since Google is returning those now.
diff --git a/Changes b/Changes index 69018b7..28b36cf 100644 --- a/Changes +++ b/Changes @@ -1,49 +1,51 @@ Revision history for Perl extension Net::Google::Spreadsheets + - change default feed URL to use SSL, since Google is returning those now + 0.12 Sun Jul 07 13:00:00 2010 - fixed getting table error (thanks to sartak) - added documentations on tables, rows (thanks to siguc) - fixed num_rows property of Table was not working (thanks to Yan Wong, #57540) 0.11 Thu Apr 22 16:10:00 2010 - added documentation on deleteing items (thanks to siguc) 0.10 Mon Mar 15 23:49:00 2010 - update dependencies (Mouse 0.51, Net::Google::DataAPI 0.17) 0.09 Sun Mar 07 23:27:00 2010 - Fix spreadsheet key changes (thanks to Colin Magee) 0.08 Thu Dec 31 19:20:30 2009 - follow Net::Google::DataAPI changes - update POD 0.07 Fri Dec 22 22:53:34 2009 - now uses Net::Google::DataAPI - AuthSub and OAuth support via Net::Google::DataAPI - now uses Any::Moose 0.06 Thu Aug 20 23:21:35 2009 - Refactored internals 0.06_01 Mon Arg 16 16:01:27 2009 - Supports Google Spreadsheets API version 3.0 - Add table and record feeds supports - Better error handlings (no more redirects, captures xml parse error, and more) - Refactored internals 0.05 Sun Aug 15 09:47:50 2009 - Fix Moose attribute problem #48627 (thanks to Eric Celeste, IMALPASS) 0.04 Wed Apr 15 09:22:59 2009 - Updated POD (thanks to Mr. Grue) 0.03 Sun Apr 05 13:22:21 2009 - param method for Net::Google::Spreadsheets::Row (thanks to Mr. Grue) 0.02 Sat Apr 04 22:32:40 2009 - Crypt::SSLeay dependency - Better error message on login failure (thanks to Mr. Grue) 0.01 Tue Dec 16 23:52:25 2008 - original version diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index e5b9391..d42c617 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,351 +1,351 @@ package Net::Google::Spreadsheets; use Any::Moose; use Net::Google::DataAPI; use namespace::autoclean; use 5.008001; use Net::Google::AuthSub; use Net::Google::DataAPI::Auth::AuthSub; our $VERSION = '0.12'; with 'Net::Google::DataAPI::Role::Service'; has gdata_version => ( is => 'ro', isa => 'Str', default => '3.0' ); has namespaces => ( is => 'ro', isa => 'HashRef', default => sub { { gs => 'http://schemas.google.com/spreadsheets/2006', gsx => 'http://schemas.google.com/spreadsheets/2006/extended', batch => 'http://schemas.google.com/gdata/batch', } }, ); has username => (is => 'ro', isa => 'Str'); has password => (is => 'ro', isa => 'Str'); has account_type => (is => 'ro', isa => 'Str', required => 1, default => 'HOSTED_OR_GOOGLE'); has source => (is => 'ro', isa => 'Str', required => 1, default => __PACKAGE__ . '-' . $VERSION); sub _build_auth { my ($self) = @_; my $authsub = Net::Google::AuthSub->new( source => $self->source, service => 'wise', account_type => $self->account_type, ); my $res = $authsub->login( $self->username, $self->password ); unless ($res && $res->is_success) { die 'Net::Google::AuthSub login failed'; } return Net::Google::DataAPI::Auth::AuthSub->new( authsub => $authsub, ); } feedurl spreadsheet => ( - default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full', + default => 'https://spreadsheets.google.com/feeds/spreadsheets/private/full', entry_class => 'Net::Google::Spreadsheets::Spreadsheet', can_add => 0, ); around spreadsheets => sub { my ($next, $self, $args) = @_; my @result = $next->($self, $args); if (my $key = $args->{key}) { @result = grep {$_->key eq $key} @result; } return @result; }; sub BUILD { my $self = shift; $self->auth; } __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, {row => 1, col => 4, input_value => 'age'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # fetch rows my @rows = $worksheet->rows; # or fetch rows with query @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); # delete the row $row->delete; # delete the worksheet $worksheet->delete; # create a table my $table = $spreadsheet->add_table( { worksheet => $new_worksheet, columns => ['name', 'nick', 'mail address', 'age'], } ); # add a record my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', 'mail address' => '[email protected]', age => '33', } ); # find a record my $found = $table->record( { sq => '"mail address" = "[email protected]"' } ); # delete it $found->delete; # delete table $table->delete; =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 2 =item * username Username for Google. This should be full email address format like '[email protected]'. =item * password Password corresponding to the username. =item * source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 2 =item * title title of the spreadsheet. =item * title-exact whether title search should match exactly or not. =item * key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 AUTHORIZATIONS you can optionally pass auth object argument when initializing Net::Google::Spreadsheets instance. If you want to use AuthSub mechanism, make Net::Google::DataAPI::Auth::AuthSub object and path it to the constructor: my $authsub = Net::Google::AuthSub->new; $authsub->auth(undef, $session_token); my $service = Net::Google::Spreadsheet->new( auth => $authsub ); In OAuth case, like this: my $oauth = Net::Google::DataAPI::Auth::OAuth->new( consumer_key => 'consumer.example.com', consumer_secret => 'mys3cr3t', callback => 'http://consumer.example.com/callback', ); $oauth->get_request_token; my $url = $oauth->get_authorize_token_url; # show the url to the user and get the $verifier value $oauth->get_access_token({verifier => $verifier}); my $service = Net::Google::Spreadsheet->new( auth => $oauth ); =head1 TESTING To test this module, you have to prepare as below. =over 2 =item * create a spreadsheet by hand Go to L<http://docs.google.com> and create a spreadsheet. =item * set SPREADSHEET_TITLE environment variable export SPREADSHEET_TITLE='my test spreadsheet' or so. =item * set username and password for google.com via Config::Pit install Config::Pit and type ppit set google.com then some editor comes up and type your username and password like --- username: [email protected] password: foobarbaz =item * run tests as always, perl Makefile.PL make make test =back =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::DataAPI> L<Net::OAuth> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Record> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/t/02_spreadsheet.t b/t/02_spreadsheet.t index beb7447..fc14939 100644 --- a/t/02_spreadsheet.t +++ b/t/02_spreadsheet.t @@ -1,47 +1,47 @@ use t::Util; use Test::More; use Test::Exception; ok my $service = service; { my @sheets = $service->spreadsheets; ok scalar @sheets; isa_ok $sheets[0], 'Net::Google::Spreadsheets::Spreadsheet'; ok $sheets[0]->title; ok $sheets[0]->key; ok $sheets[0]->etag; } { ok my $ss = spreadsheet; isa_ok $ss, 'Net::Google::Spreadsheets::Spreadsheet'; is $ss->title, $t::Util::SPREADSHEET_TITLE; - like $ss->id, qr{^http://spreadsheets.google.com/feeds/spreadsheets/}; + like $ss->id, qr{^https://spreadsheets.google.com/feeds/spreadsheets/}; isa_ok $ss->author, 'XML::Atom::Person'; is $ss->author->email, config->{username}; my $key = $ss->key; ok length $key, 'key defined'; my $ss2 = $service->spreadsheet({key => $key}); ok $ss2; isa_ok $ss2, 'Net::Google::Spreadsheets::Spreadsheet'; is $ss2->key, $key; is $ss2->title, $t::Util::SPREADSHEET_TITLE; throws_ok { $ss2->title('foobar') } qr{Cannot assign a value to a read-only accessor}; } { my @existing = map {$_->title} $service->spreadsheets; my $title; while (1) { $title = 'spreadsheet created at '.scalar localtime; grep {$_ eq $title} @existing or last; } my $ss = $service->spreadsheet({title => $title}); is $ss, undef, "spreadsheet named '$title' shouldn't exit"; my @ss = $service->spreadsheets({title => $title}); is scalar @ss, 0; } done_testing;
lopnor/Net-Google-Spreadsheets
6eddfa3ae7e2f551b1de7980781d9532e842dfa8
Checking in changes prior to tagging of version 0.12.
diff --git a/Changes b/Changes index a2d8ea8..69018b7 100644 --- a/Changes +++ b/Changes @@ -1,48 +1,49 @@ Revision history for Perl extension Net::Google::Spreadsheets -0.12 Sun Apr 24 13:50:00 2010 +0.12 Sun Jul 07 13:00:00 2010 - fixed getting table error (thanks to sartak) - added documentations on tables, rows (thanks to siguc) + - fixed num_rows property of Table was not working (thanks to Yan Wong, #57540) 0.11 Thu Apr 22 16:10:00 2010 - added documentation on deleteing items (thanks to siguc) 0.10 Mon Mar 15 23:49:00 2010 - update dependencies (Mouse 0.51, Net::Google::DataAPI 0.17) 0.09 Sun Mar 07 23:27:00 2010 - Fix spreadsheet key changes (thanks to Colin Magee) 0.08 Thu Dec 31 19:20:30 2009 - follow Net::Google::DataAPI changes - update POD 0.07 Fri Dec 22 22:53:34 2009 - now uses Net::Google::DataAPI - AuthSub and OAuth support via Net::Google::DataAPI - now uses Any::Moose 0.06 Thu Aug 20 23:21:35 2009 - Refactored internals 0.06_01 Mon Arg 16 16:01:27 2009 - Supports Google Spreadsheets API version 3.0 - Add table and record feeds supports - Better error handlings (no more redirects, captures xml parse error, and more) - Refactored internals 0.05 Sun Aug 15 09:47:50 2009 - Fix Moose attribute problem #48627 (thanks to Eric Celeste, IMALPASS) 0.04 Wed Apr 15 09:22:59 2009 - Updated POD (thanks to Mr. Grue) 0.03 Sun Apr 05 13:22:21 2009 - param method for Net::Google::Spreadsheets::Row (thanks to Mr. Grue) 0.02 Sat Apr 04 22:32:40 2009 - Crypt::SSLeay dependency - Better error message on login failure (thanks to Mr. Grue) 0.01 Tue Dec 16 23:52:25 2008 - original version diff --git a/Makefile.PL b/Makefile.PL index 764b721..d0c1322 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,26 +1,26 @@ use inc::Module::Install; name 'Net-Google-Spreadsheets'; all_from 'lib/Net/Google/Spreadsheets.pm'; requires 'Carp'; requires 'XML::Atom'; requires 'Net::Google::AuthSub'; -requires 'Net::Google::DataAPI' => '0.17'; +requires 'Net::Google::DataAPI' => '0.19'; requires 'URI'; requires 'namespace::autoclean'; requires_any_moose( moose => '0.56', mouse => '0.51', ); tests_recursive; author_tests 'xt'; build_requires 'Test::More' => '0.88'; build_requires 'Test::Exception'; build_requires 'Test::MockModule'; build_requires 'Test::MockObject'; use_test_base; auto_include; auto_set_repository; WriteAll; diff --git a/lib/Net/Google/Spreadsheets/Record.pm b/lib/Net/Google/Spreadsheets/Record.pm index 40c3d50..d45f23f 100644 --- a/lib/Net/Google/Spreadsheets/Record.pm +++ b/lib/Net/Google/Spreadsheets/Record.pm @@ -1,136 +1,136 @@ package Net::Google::Spreadsheets::Record; use Any::Moose; use namespace::autoclean; use XML::Atom::Util qw(nodelist); with 'Net::Google::DataAPI::Role::Entry', 'Net::Google::DataAPI::Role::HasContent'; after from_atom => sub { my ($self) = @_; for my $node (nodelist($self->elem, $self->ns('gs')->{uri}, 'field')) { - $self->{content}->{$node->getAttribute('name')} = $node->textContent; + $self->content->{$node->getAttribute('name')} = $node->textContent; } }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); - while (my ($key, $value) = each %{$self->{content}}) { + while (my ($key, $value) = each %{$self->content}) { $entry->add($self->ns('gs'), 'field', $value, {name => $key}); } return $entry; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Record - A representation class for Google Spreadsheet record. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a record my $record = $service->spreadsheet( { title => 'list for new year cards', } )->table( { title => 'addressbook', } )->record( { sq => 'id = 1000', } ); # get the content of a row my $hashref = $record->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $record->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $record->param('name'); # returns 'Nobuo Danjou' # you can also get it via content like this: my $value_via_content = $record->content->{name}; my $newval = $record->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new record value (with all fields) my $hashref2 = $record->param; # same as $record->content; # setting whole new content $record->content( { id => 8080, address => 'nowhere', zip => '999-9999', name => 'nowhere man' } ); # delete a record $record->delete; =head1 METHODS =head2 param sets and gets content value. =head2 delete deletes the record. =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Row> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Row.pm b/lib/Net/Google/Spreadsheets/Row.pm index d84bfcc..804d3d3 100644 --- a/lib/Net/Google/Spreadsheets/Row.pm +++ b/lib/Net/Google/Spreadsheets/Row.pm @@ -1,171 +1,171 @@ package Net::Google::Spreadsheets::Row; use Any::Moose; use namespace::autoclean; use Net::Google::DataAPI; use XML::Atom::Util qw(nodelist); with 'Net::Google::DataAPI::Role::Entry', 'Net::Google::DataAPI::Role::HasContent'; after from_atom => sub { my ($self) = @_; for my $node (nodelist($self->elem, $self->ns('gsx')->{uri}, '*')) { - $self->{content}->{$node->localname} = $node->textContent; + $self->content->{$node->localname} = $node->textContent; } }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); - while (my ($key, $value) = each %{$self->{content}}) { + while (my ($key, $value) = each %{$self->content}) { $entry->set($self->ns('gsx'), $key, $value); } return $entry; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Row - A representation class for Google Spreadsheet row. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a row my $row = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->row( { sq => 'id = 1000' } ); # get the content of a row my $hashref = $row->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $row->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $row->param('name'); # returns 'Nobuo Danjou' # it's same by getting via param method without args, or content method: my $value_by_param = $row->param->{name}; my $value_by_content = $row->content->{name}; my $newval = $row->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new row value (with all fields) my $hashref2 = $row->param; # same as $row->content; # delete the row $row->delete; =head1 METHODS =head2 param sets and gets content value. =head2 delete deletes the row. =head1 CAVEATS Space characters in hash key of rows will be removed when you access rows. See below. my $ws = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'})->worksheet(1); $ws->batchupdate_cell( {col => 1,row => 1, input_value => 'name'}, {col => 2,row => 1, input_value => 'mail address'}, ); $ws->add_row( { name => 'my name', mailaddress => '[email protected]', # above passes, below fails. # 'mail address' => '[email protected]', } ); Instead, Net::Google::Spreadsheets::Table and Net::Google::Spreadsheets::Record allows space characters in column name. my $s = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'}); my $t = $s->add_table( { worksheet => $s->worksheet(1), columns => ['name', 'mail address'], } ); $t->add_record( { name => 'my name', 'mail address' => '[email protected]', } ); =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. So it's the same thing to get the value with param method or content attribute. my $value = $row->param('foo'); # it's same my $value2 = $row->content->{'foo'}; =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Spreadsheet.pm b/lib/Net/Google/Spreadsheets/Spreadsheet.pm index a5587cb..1f4bb27 100644 --- a/lib/Net/Google/Spreadsheets/Spreadsheet.pm +++ b/lib/Net/Google/Spreadsheets/Spreadsheet.pm @@ -1,246 +1,250 @@ package Net::Google::Spreadsheets::Spreadsheet; use Any::Moose; use namespace::autoclean; use Net::Google::DataAPI; with 'Net::Google::DataAPI::Role::Entry'; use URI; has title => ( is => 'ro', isa => 'Str', lazy_build => 1, ); entry_has key => ( isa => 'Str', is => 'ro', from_atom => sub { my ($self, $atom) = @_; my ($link) = grep { $_->rel eq 'alternate' && $_->type eq 'text/html' } $atom->link; return {URI->new($link->href)->query_form}->{key}; }, ); feedurl worksheet => ( entry_class => 'Net::Google::Spreadsheets::Worksheet', as_content_src => 1, ); feedurl table => ( entry_class => 'Net::Google::Spreadsheets::Table', rel => 'http://schemas.google.com/spreadsheets/2006#tablesfeed', ); __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Spreadsheet - Representation of spreadsheet. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # create a worksheet my $worksheet = $spreadsheet->add_worksheet( { title => 'foobar', col_count => 10, row_count => 100, } ); # list worksheets my @ws = $spreadsheet->worksheets; # find a worksheet my $ws = $spreadsheet->worksheet({title => 'fooba'}); # create a table my $table = $spreadsheet->add_table( { title => 'sample table', worksheet => $worksheet, columns => ['id', 'username', 'mail', 'password'], } ); # list tables my @t = $spreadsheet->tables; # find a worksheet my $t = $spreadsheet->table({title => 'sample table'}); =head1 METHODS =head2 worksheets(\%condition) Returns a list of Net::Google::Spreadsheets::Worksheet objects. Acceptable arguments are: =over 2 =item * title =item * title-exact =back =head2 worksheet(\%condition) Returns first item of worksheets(\%condition) if available. =head2 add_worksheet(\%attribuets) Creates new worksheet and returns a Net::Google::Spreadsheets::Worksheet object representing it. Arguments (all optional) are: =over 2 =item * title =item * col_count =item * row_count =back =head2 tables(\%condition) Returns a list of Net::Google::Spreadsheets::Table objects. Acceptable arguments are: =over 2 =item * title =item * title-exact =back =head2 table(\%condition) Returns first item of tables(\%condition) if available. =head2 add_table(\%attribuets) Creates new table and returns a Net::Google::Spreadsheets::Table object representing it. Arguments are: =over 2 =item * title (optional) =item * summary (optional) =item * worksheet Worksheet where the table lives. worksheet instance or the title. =item * header (optional, default = 1) Row number of header =item * start_row (optional, default = 2) The index of the first row of the data section. +=item * num_rows (optional, default = 0) + +Number of rows of the data section initially made. + =item * insertion_mode (optional, default = 'overwrite') Insertion mode. 'insert' inserts new row into the worksheet when creating record, 'overwrite' tries to use existing rows in the worksheet. =item * columns Columns of the table. you can specify them as hashref, arrayref, arrayref of hashref. $ss->add_table( { worksheet => $ws, columns => [ {index => 1, name => 'foo'}, {index => 2, name => 'bar'}, {index => 3, name => 'baz'}, ], } ); $ss->add_table( { worksheet => $ws, columns => { A => 'foo', B => 'bar', C => 'baz', } } ); $ss->add_table( { worksheet => $ws, columns => ['foo', 'bar', 'baz'], } ); 'index' of the first case and hash key of the second case is column index of the worksheet. In the third case, the columns is automatically placed to the columns of the worksheet from 'A' to 'Z' order. =back =head1 DELETING A SPREADSHEET To delete a spreadsheet, use L<Net::Google::DocumentsList>. my $docs = Net::Google::DocumentsList->new( username => '[email protected]', password => 'mypassword' ); $docs->item({resource_id => 'spreadsheet:'. $ss->key})->delete; =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Table> L<Net::Google::DocumentsList> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/t/06_table.t b/t/06_table.t index 4029efd..e02097b 100644 --- a/t/06_table.t +++ b/t/06_table.t @@ -1,103 +1,105 @@ use t::Util; use Test::More; my $ws_title = 'test worksheet for table '.scalar localtime; my $table_title = 'test table '.scalar localtime; my $ss = spreadsheet; ok my $ws = $ss->add_worksheet({title => $ws_title}), 'add worksheet'; is $ws->title, $ws_title; my @t = $ss->tables; my $previous_table_count = scalar @t; { ok my $table = $ss->add_table( { title => $table_title, summary => 'this is summary of this table', worksheet => $ws, header => 1, start_row => 2, + num_rows => 15, columns => [ {index => 1, name => 'name'}, {index => 2, name => 'mail address'}, {index => 3, name => 'nick'}, ], } ); isa_ok $table, 'Net::Google::Spreadsheets::Table'; } { my @t = $ss->tables; ok scalar @t; is scalar @t, $previous_table_count + 1; isa_ok $t[0], 'Net::Google::Spreadsheets::Table'; } { ok my $t = $ss->table({title => $table_title}); isa_ok $t, 'Net::Google::Spreadsheets::Table'; is $t->title, $table_title; is $t->summary, 'this is summary of this table'; is $t->worksheet, $ws->title; is $t->header, 1; is $t->start_row, 2; + is $t->num_rows, 15; is scalar @{$t->columns}, 3; ok grep {$_->name eq 'name' && $_->index eq 'A'} @{$t->columns}; ok grep {$_->name eq 'mail address' && $_->index eq 'B'} @{$t->columns}; ok grep {$_->name eq 'nick' && $_->index eq 'C'} @{$t->columns}; } { ok my $t = $ss->table; isa_ok $t, 'Net::Google::Spreadsheets::Table'; ok $t->delete; my @t = $ss->tables; is scalar @t, $previous_table_count; } ok $ws->delete, 'delete worksheet'; for my $mode (qw(overwrite insert)) { ok my $ws2 = $ss->add_worksheet( { title => 'insertion mode test '.scalar localtime, col_count => 3, row_count => 3, } ), 'add worksheet'; ok $ss->add_table( { title => 'foobarbaz', worksheet => $ws2, insertion_mode => $mode, start_row => 3, columns => ['foo', 'bar', 'baz'], } ); ok my $t = $ss->table({title => 'foobarbaz', worksheet => $ws2->title}); isa_ok $t, 'Net::Google::Spreadsheets::Table'; is $t->title, 'foobarbaz', 'table title'; is $t->worksheet, $ws2->title, 'worksheet name'; is $t->insertion_mode, $mode, 'insertion mode'; is $t->start_row, 3, 'start row'; my @c = @{$t->columns}; is scalar @c, 3, 'column count is 3'; ok grep({$_->name eq 'foo' && $_->index eq 'A'} @c), 'column foo exists'; ok grep({$_->name eq 'bar' && $_->index eq 'B'} @c), 'column bar exists'; ok grep({$_->name eq 'baz' && $_->index eq 'C'} @c), 'column baz exists'; for my $i (1 .. 3) { ok $t->add_record( { foo => 1, bar => 2, baz => 3, } ); is $t->num_rows, $i; } ok $ws2->delete; } done_testing; diff --git a/t/07_record.t b/t/07_record.t index 24d732d..5e3d0a4 100644 --- a/t/07_record.t +++ b/t/07_record.t @@ -1,70 +1,70 @@ use t::Util; use Test::More; my $ws_title = 'test worksheet for record '.scalar localtime; my $table_title = 'test table '.scalar localtime; my $ss = spreadsheet; ok my $ws = $ss->add_worksheet({title => $ws_title}), 'add worksheet'; is $ws->title, $ws_title; ok my $table = $ss->add_table( { worksheet => $ws, columns => [ 'name', 'mail address', 'nick', ] } ); { my $value = { name => 'Nobuo Danjou', 'mail address' => '[email protected]', nick => 'lopnor', }; ok my $record = $table->add_record($value); isa_ok $record, 'Net::Google::Spreadsheets::Record'; is_deeply $record->content, $value; is_deeply $record->param, $value; is $record->param('name'), $value->{name}; my $newval = {name => '檀上伸郎'}; is_deeply $record->param($newval), { %$value, %$newval, }; is_deeply $record->content,{ %$value, %$newval, }; { ok my $r = $table->record({sq => '"mail address" = "[email protected]"'}); isa_ok $r, 'Net::Google::Spreadsheets::Record'; is $r->param('mail address'), $value->{'mail address'}; } my $value2 = { name => 'Kazuhiro Osawa', nick => 'yappo', - 'mail address' => '', + 'mail address' => '[email protected]', }; $record->content($value2); is_deeply $record->content, $value2; is scalar $table->records, 1; ok $record->delete; is scalar $table->records, 0; } { $table->add_record( { name => $_ } ) for qw(danjou lopnor soffritto); is scalar $table->records, 3; ok my $record = $table->record({sq => 'name = "lopnor"'}); isa_ok $record, 'Net::Google::Spreadsheets::Record'; is_deeply $record->content, {name => 'lopnor', nick => '', 'mail address' => ''}; } ok $ws->delete, 'delete worksheet'; done_testing;
lopnor/Net-Google-Spreadsheets
5d3f42c6621aa38f194dad0ee14d858c8a5551d1
changes at osdc.tw
diff --git a/Changes b/Changes index 3292007..a2d8ea8 100644 --- a/Changes +++ b/Changes @@ -1,44 +1,48 @@ Revision history for Perl extension Net::Google::Spreadsheets +0.12 Sun Apr 24 13:50:00 2010 + - fixed getting table error (thanks to sartak) + - added documentations on tables, rows (thanks to siguc) + 0.11 Thu Apr 22 16:10:00 2010 - added documentation on deleteing items (thanks to siguc) 0.10 Mon Mar 15 23:49:00 2010 - update dependencies (Mouse 0.51, Net::Google::DataAPI 0.17) 0.09 Sun Mar 07 23:27:00 2010 - Fix spreadsheet key changes (thanks to Colin Magee) 0.08 Thu Dec 31 19:20:30 2009 - follow Net::Google::DataAPI changes - update POD 0.07 Fri Dec 22 22:53:34 2009 - now uses Net::Google::DataAPI - AuthSub and OAuth support via Net::Google::DataAPI - now uses Any::Moose 0.06 Thu Aug 20 23:21:35 2009 - Refactored internals 0.06_01 Mon Arg 16 16:01:27 2009 - Supports Google Spreadsheets API version 3.0 - Add table and record feeds supports - Better error handlings (no more redirects, captures xml parse error, and more) - Refactored internals 0.05 Sun Aug 15 09:47:50 2009 - Fix Moose attribute problem #48627 (thanks to Eric Celeste, IMALPASS) 0.04 Wed Apr 15 09:22:59 2009 - Updated POD (thanks to Mr. Grue) 0.03 Sun Apr 05 13:22:21 2009 - param method for Net::Google::Spreadsheets::Row (thanks to Mr. Grue) 0.02 Sat Apr 04 22:32:40 2009 - Crypt::SSLeay dependency - Better error message on login failure (thanks to Mr. Grue) 0.01 Tue Dec 16 23:52:25 2008 - original version diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index a96d6c6..e5b9391 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,351 +1,351 @@ package Net::Google::Spreadsheets; use Any::Moose; use Net::Google::DataAPI; use namespace::autoclean; use 5.008001; use Net::Google::AuthSub; use Net::Google::DataAPI::Auth::AuthSub; -our $VERSION = '0.11'; +our $VERSION = '0.12'; with 'Net::Google::DataAPI::Role::Service'; has gdata_version => ( is => 'ro', isa => 'Str', default => '3.0' ); has namespaces => ( is => 'ro', isa => 'HashRef', default => sub { { gs => 'http://schemas.google.com/spreadsheets/2006', gsx => 'http://schemas.google.com/spreadsheets/2006/extended', batch => 'http://schemas.google.com/gdata/batch', } }, ); has username => (is => 'ro', isa => 'Str'); has password => (is => 'ro', isa => 'Str'); has account_type => (is => 'ro', isa => 'Str', required => 1, default => 'HOSTED_OR_GOOGLE'); has source => (is => 'ro', isa => 'Str', required => 1, default => __PACKAGE__ . '-' . $VERSION); sub _build_auth { my ($self) = @_; my $authsub = Net::Google::AuthSub->new( source => $self->source, service => 'wise', account_type => $self->account_type, ); my $res = $authsub->login( $self->username, $self->password ); unless ($res && $res->is_success) { die 'Net::Google::AuthSub login failed'; } return Net::Google::DataAPI::Auth::AuthSub->new( authsub => $authsub, ); } feedurl spreadsheet => ( default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full', entry_class => 'Net::Google::Spreadsheets::Spreadsheet', can_add => 0, ); around spreadsheets => sub { my ($next, $self, $args) = @_; my @result = $next->($self, $args); if (my $key = $args->{key}) { @result = grep {$_->key eq $key} @result; } return @result; }; sub BUILD { my $self = shift; $self->auth; } __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, {row => 1, col => 4, input_value => 'age'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # fetch rows my @rows = $worksheet->rows; # or fetch rows with query @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); # delete the row $row->delete; # delete the worksheet $worksheet->delete; # create a table my $table = $spreadsheet->add_table( { worksheet => $new_worksheet, columns => ['name', 'nick', 'mail address', 'age'], } ); # add a record my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', 'mail address' => '[email protected]', age => '33', } ); # find a record my $found = $table->record( { sq => '"mail address" = "[email protected]"' } ); # delete it $found->delete; # delete table $table->delete; =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 2 =item * username Username for Google. This should be full email address format like '[email protected]'. =item * password Password corresponding to the username. =item * source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 2 =item * title title of the spreadsheet. =item * title-exact whether title search should match exactly or not. =item * key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 AUTHORIZATIONS you can optionally pass auth object argument when initializing Net::Google::Spreadsheets instance. If you want to use AuthSub mechanism, make Net::Google::DataAPI::Auth::AuthSub object and path it to the constructor: my $authsub = Net::Google::AuthSub->new; $authsub->auth(undef, $session_token); my $service = Net::Google::Spreadsheet->new( auth => $authsub ); In OAuth case, like this: my $oauth = Net::Google::DataAPI::Auth::OAuth->new( consumer_key => 'consumer.example.com', consumer_secret => 'mys3cr3t', callback => 'http://consumer.example.com/callback', ); $oauth->get_request_token; my $url = $oauth->get_authorize_token_url; # show the url to the user and get the $verifier value $oauth->get_access_token({verifier => $verifier}); my $service = Net::Google::Spreadsheet->new( auth => $oauth ); =head1 TESTING To test this module, you have to prepare as below. =over 2 =item * create a spreadsheet by hand Go to L<http://docs.google.com> and create a spreadsheet. =item * set SPREADSHEET_TITLE environment variable export SPREADSHEET_TITLE='my test spreadsheet' or so. =item * set username and password for google.com via Config::Pit install Config::Pit and type ppit set google.com then some editor comes up and type your username and password like --- username: [email protected] password: foobarbaz =item * run tests as always, perl Makefile.PL make make test =back =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::DataAPI> L<Net::OAuth> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Record> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Net/Google/Spreadsheets/Record.pm b/lib/Net/Google/Spreadsheets/Record.pm index d4c6367..40c3d50 100644 --- a/lib/Net/Google/Spreadsheets/Record.pm +++ b/lib/Net/Google/Spreadsheets/Record.pm @@ -1,124 +1,136 @@ package Net::Google::Spreadsheets::Record; use Any::Moose; use namespace::autoclean; use XML::Atom::Util qw(nodelist); with 'Net::Google::DataAPI::Role::Entry', 'Net::Google::DataAPI::Role::HasContent'; after from_atom => sub { my ($self) = @_; for my $node (nodelist($self->elem, $self->ns('gs')->{uri}, 'field')) { $self->{content}->{$node->getAttribute('name')} = $node->textContent; } }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->{content}}) { $entry->add($self->ns('gs'), 'field', $value, {name => $key}); } return $entry; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Record - A representation class for Google Spreadsheet record. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a record my $record = $service->spreadsheet( { title => 'list for new year cards', } )->table( { title => 'addressbook', } )->record( { sq => 'id = 1000', } ); # get the content of a row my $hashref = $record->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $record->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $record->param('name'); # returns 'Nobuo Danjou' + # you can also get it via content like this: + my $value_via_content = $record->content->{name}; my $newval = $record->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new record value (with all fields) my $hashref2 = $record->param; # same as $record->content; + + # setting whole new content + $record->content( + { + id => 8080, + address => 'nowhere', + zip => '999-9999', + name => 'nowhere man' + } + ); # delete a record $record->delete; =head1 METHODS =head2 param sets and gets content value. =head2 delete deletes the record. =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Row> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Row.pm b/lib/Net/Google/Spreadsheets/Row.pm index 2103f90..d84bfcc 100644 --- a/lib/Net/Google/Spreadsheets/Row.pm +++ b/lib/Net/Google/Spreadsheets/Row.pm @@ -1,162 +1,171 @@ package Net::Google::Spreadsheets::Row; use Any::Moose; use namespace::autoclean; use Net::Google::DataAPI; use XML::Atom::Util qw(nodelist); with 'Net::Google::DataAPI::Role::Entry', 'Net::Google::DataAPI::Role::HasContent'; after from_atom => sub { my ($self) = @_; for my $node (nodelist($self->elem, $self->ns('gsx')->{uri}, '*')) { $self->{content}->{$node->localname} = $node->textContent; } }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->{content}}) { $entry->set($self->ns('gsx'), $key, $value); } return $entry; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Row - A representation class for Google Spreadsheet row. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a row my $row = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->row( { sq => 'id = 1000' } ); # get the content of a row my $hashref = $row->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $row->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $row->param('name'); # returns 'Nobuo Danjou' + + # it's same by getting via param method without args, or content method: + my $value_by_param = $row->param->{name}; + my $value_by_content = $row->content->{name}; my $newval = $row->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new row value (with all fields) my $hashref2 = $row->param; # same as $row->content; # delete the row $row->delete; =head1 METHODS =head2 param sets and gets content value. =head2 delete deletes the row. =head1 CAVEATS Space characters in hash key of rows will be removed when you access rows. See below. my $ws = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'})->worksheet(1); $ws->batchupdate_cell( {col => 1,row => 1, input_value => 'name'}, {col => 2,row => 1, input_value => 'mail address'}, ); $ws->add_row( { name => 'my name', mailaddress => '[email protected]', # above passes, below fails. # 'mail address' => '[email protected]', } ); Instead, Net::Google::Spreadsheets::Table and Net::Google::Spreadsheets::Record allows space characters in column name. my $s = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'}); my $t = $s->add_table( { worksheet => $s->worksheet(1), columns => ['name', 'mail address'], } ); $t->add_record( { name => 'my name', 'mail address' => '[email protected]', } ); =head1 ATTRIBUTES =head2 content -Rewritable attribute. You can get and set the value. +Rewritable attribute. You can get and set the value. +So it's the same thing to get the value with param method or content attribute. + + my $value = $row->param('foo'); + # it's same + my $value2 = $row->content->{'foo'}; =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Table.pm b/lib/Net/Google/Spreadsheets/Table.pm index 2402cac..683d3b4 100644 --- a/lib/Net/Google/Spreadsheets/Table.pm +++ b/lib/Net/Google/Spreadsheets/Table.pm @@ -1,228 +1,236 @@ package Net::Google::Spreadsheets::Table; use Any::Moose; use Any::Moose '::Util::TypeConstraints'; use namespace::autoclean; use Net::Google::DataAPI; use XML::Atom::Util qw(nodelist first create_element); +use Net::Google::Spreadsheets::Worksheet; +use Net::Google::Spreadsheets::Record; with 'Net::Google::DataAPI::Role::Entry'; subtype 'ColumnList' => as 'ArrayRef[Net::Google::Spreadsheets::Table::Column]'; coerce 'ColumnList' => from 'ArrayRef[HashRef]' => via { [ map {Net::Google::Spreadsheets::Table::Column->new($_)} @$_ ] }; coerce 'ColumnList' => from 'ArrayRef[Str]' => via { my @c; my $index = 0; for my $value (@$_) { push @c, Net::Google::Spreadsheets::Table::Column->new( index => ++$index, name => $value, ); } \@c; }; coerce 'ColumnList' => from 'HashRef' => via { my @c; while (my ($key, $value) = each(%$_)) { push @c, Net::Google::Spreadsheets::Table::Column->new( index => $key, name => $value, ); } \@c; }; subtype 'WorksheetName' => as 'Str'; coerce 'WorksheetName' => from 'Net::Google::Spreadsheets::Worksheet' => via { $_->title }; feedurl record => ( entry_class => 'Net::Google::Spreadsheets::Record', arg_builder => sub { my ($self, $args) = @_; return {content => $args}; }, as_content_src => 1, ); has summary => ( is => 'rw', isa => 'Str' ); has worksheet => ( is => 'ro', isa => 'WorksheetName', coerce => 1 ); has header => ( is => 'ro', isa => 'Int', required => 1, default => 1 ); has start_row => ( is => 'ro', isa => 'Int', required => 1, default => 2 ); has num_rows => ( is => 'ro', isa => 'Int' ); has columns => ( is => 'ro', isa => 'ColumnList', coerce => 1 ); has insertion_mode => ( is => 'ro', isa => (enum ['insert', 'overwrite']), default => 'overwrite' ); after from_atom => sub { my ($self) = @_; my $gsns = $self->ns('gs')->{uri}; my $elem = $self->elem; $self->{summary} = $self->atom->summary; $self->{worksheet} = first( $elem, $gsns, 'worksheet')->getAttribute('name'); $self->{header} = first( $elem, $gsns, 'header')->getAttribute('row'); my @columns; my $data = first($elem, $gsns, 'data'); $self->{insertion_mode} = $data->getAttribute('insertionMode'); $self->{start_row} = $data->getAttribute('startRow'); $self->{num_rows} = $data->getAttribute('numRows'); for (nodelist($data, $gsns, 'column')) { push @columns, Net::Google::Spreadsheets::Table::Column->new( index => $_->getAttribute('index'), name => $_->getAttribute('name'), ); } $self->{columns} = \@columns; }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); my $gsns = $self->ns('gs')->{uri}; $entry->summary($self->summary) if $self->summary; $entry->set($gsns, 'worksheet', '', {name => $self->worksheet}); $entry->set($gsns, 'header', '', {row => $self->header}); my $data = create_element($gsns, 'data'); $data->setAttribute(startRow => $self->start_row); $data->setAttribute(insertionMode => $self->insertion_mode); - $data->setAttribute(startRow => $self->start_row) if $self->start_row; + $data->setAttribute(numRows => $self->num_rows) if $self->num_rows; for ( @{$self->columns} ) { my $column = create_element($gsns, 'column'); $column->setAttribute(index => $_->index); $column->setAttribute(name => $_->name); $data->appendChild($column); } $entry->set($gsns, 'data', $data); return $entry; }; __PACKAGE__->meta->make_immutable; package # hide from PAUSE Net::Google::Spreadsheets::Table::Column; use Any::Moose; has 'index' => ( is => 'ro', isa => 'Str' ); has 'name' => ( is => 'ro', isa => 'Str' ); __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Table - A representation class for Google Spreadsheet table. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a table my $table = $service->spreadsheet( { title => 'list for new year cards', } )->table( { title => 'sample table', } ); # create a record my $r = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # get records my @records = $table->records; # search records @records = $table->records({sq => 'age > 20'}); # search a record my $record = $table->record({sq => 'name = "Nobuo Danjou"'}); =head1 METHODS =head2 records(\%condition) Returns a list of Net::Google::Spreadsheets::Record objects. Acceptable arguments are: =over 2 =item * sq Structured query on the full text in the worksheet. see the URL below for detail. =item * orderby Set column name to use for ordering. =item * reverse -Set 'true' or 'false'. The default is 'false'. +Set 'true' or 'false'. The default is 'false'. It reverses the order. =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#RecordParameters> for details. =head2 record(\%condition) Returns first item of records(\%condition) if available. =head2 add_record(\%contents) Creates new record and returns a Net::Google::Spreadsheets::Record object representing it. Arguments are contents of a row as a hashref. my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); +=head1 CAVEATS + +You can access to the table structure and records only from the Google Spreadsheets API. It means you can't create tables, add records or delete tables via web interface. It will make some problems if you want to access the data both from API and web interface. In that case, you should use $worksheets->row(s) methods instead. See the documents below for details: + +L<http://code.google.com/intl/en/apis/spreadsheets/data/3.0/developers_guide_protocol.html#TableFeeds> + =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Record> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Worksheet.pm b/lib/Net/Google/Spreadsheets/Worksheet.pm index 7def528..8c54f1b 100644 --- a/lib/Net/Google/Spreadsheets/Worksheet.pm +++ b/lib/Net/Google/Spreadsheets/Worksheet.pm @@ -1,257 +1,258 @@ package Net::Google::Spreadsheets::Worksheet; use Any::Moose; use namespace::autoclean; use Net::Google::DataAPI; with 'Net::Google::DataAPI::Role::Entry'; use Carp; use Net::Google::Spreadsheets::Cell; use XML::Atom::Util qw(first); feedurl row => ( entry_class => 'Net::Google::Spreadsheets::Row', as_content_src => 1, arg_builder => sub { my ($self, $args) = @_; return {content => $args}; }, ); feedurl cell => ( entry_class => 'Net::Google::Spreadsheets::Cell', can_add => 0, rel => 'http://schemas.google.com/spreadsheets/2006#cellsfeed', query_builder => sub { my ($self, $args) = @_; if (my $col = delete $args->{col}) { $args->{'max-col'} = $col; $args->{'min-col'} = $col; $args->{'return-empty'} = 'true'; } if (my $row = delete $args->{row}) { $args->{'max-row'} = $row; $args->{'min-row'} = $row; $args->{'return-empty'} = 'true'; } return $args; }, ); entry_has row_count => ( isa => 'Int', is => 'rw', default => 100, tagname => 'rowCount', ns => 'gs', ); entry_has col_count => ( isa => 'Int', is => 'rw', default => 20, tagname => 'colCount', ns => 'gs', ); __PACKAGE__->meta->make_immutable; sub batchupdate_cell { my ($self, @args) = @_; my $feed = XML::Atom::Feed->new; for ( @args ) { my $id = sprintf("%s/R%sC%s",$self->cell_feedurl, $_->{row}, $_->{col}); $_->{id} = $_->{editurl} = $id; $_->{container} = $self, my $entry = Net::Google::Spreadsheets::Cell->new($_)->to_atom; $entry->set($self->ns('batch'), operation => '', {type => 'update'}); $entry->set($self->ns('batch'), id => $id); $feed->add_entry($entry); } my $res_feed = $self->service->post( $self->cell_feedurl."/batch", $feed, {'If-Match' => '*'} ); $self->sync; return map { Net::Google::Spreadsheets::Cell->new( atom => $_, container => $self, ) } grep { my $node = first( $_->elem, $self->ns('batch')->{uri}, 'status' ); $node->getAttribute('code') == 200; } $res_feed->entries; } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Worksheet - Representation of worksheet. =head1 SYNOPSIS my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); my $ss = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); my $worksheet = $ss->worksheet({title => 'Sheet1'}); # update cell by batch request $worksheet->batchupdate_cell( {col => 1, row => 1, input_value => 'name'}, {col => 2, row => 1, input_value => 'nick'}, {col => 3, row => 1, input_value => 'mail'}, {col => 4, row => 1, input_value => 'age'}, ); # get a cell object my $cell = $worksheet->cell({col => 1, row => 1}); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # get rows my @rows = $worksheet->rows; # search rows @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # delete the worksheet # Note that this will fail if the worksheet is the only one # within the spreadsheet. $worksheet->delete; =head1 METHODS =head2 rows(\%condition) Returns a list of Net::Google::Spreadsheets::Row objects. Acceptable arguments are: =over 2 =item * sq Structured query on the full text in the worksheet. see the URL below for detail. =item * orderby Set column name to use for ordering. =item * reverse Set 'true' or 'false'. The default is 'false'. =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#ListParameters> for details. +Note that 'the first row of the worksheet' you can see with the browser is 'header' for the rows, so you can't get it with this method. Use cell(s) method instead if you need to access them. =head2 row(\%condition) Returns first item of rows(\%condition) if available. =head2 add_row(\%contents) Creates new row and returns a Net::Google::Spreadsheets::Row object representing it. Arguments are contents of a row as a hashref. my $row = $ws->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); =head2 cells(\%args) Returns a list of Net::Google::Spreadsheets::Cell objects. Acceptable arguments are: =over 2 =item * min-row =item * max-row =item * min-col =item * max-col =item * range =item * return-empty =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#CellParameters> for details. =head2 cell(\%args) Returns Net::Google::Spreadsheets::Cell object. Arguments are: =over 2 =item * col =item * row =back =head2 batchupdate_cell(@args) update multiple cells with a batch request. Pass a list of hash references containing: =over 2 =item * col =item * row =item * input_value =back =head2 delete Deletes the worksheet. Note that this will fail if the worksheet is only one within the spreadsheet. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut
lopnor/Net-Google-Spreadsheets
e1f503ffc0bff431ed1463691db6882b740182e6
Checking in changes prior to tagging of version 0.11.
diff --git a/Changes b/Changes index a177220..3292007 100644 --- a/Changes +++ b/Changes @@ -1,41 +1,44 @@ Revision history for Perl extension Net::Google::Spreadsheets +0.11 Thu Apr 22 16:10:00 2010 + - added documentation on deleteing items (thanks to siguc) + 0.10 Mon Mar 15 23:49:00 2010 - update dependencies (Mouse 0.51, Net::Google::DataAPI 0.17) 0.09 Sun Mar 07 23:27:00 2010 - Fix spreadsheet key changes (thanks to Colin Magee) 0.08 Thu Dec 31 19:20:30 2009 - follow Net::Google::DataAPI changes - update POD 0.07 Fri Dec 22 22:53:34 2009 - now uses Net::Google::DataAPI - AuthSub and OAuth support via Net::Google::DataAPI - now uses Any::Moose 0.06 Thu Aug 20 23:21:35 2009 - Refactored internals 0.06_01 Mon Arg 16 16:01:27 2009 - Supports Google Spreadsheets API version 3.0 - Add table and record feeds supports - Better error handlings (no more redirects, captures xml parse error, and more) - Refactored internals 0.05 Sun Aug 15 09:47:50 2009 - Fix Moose attribute problem #48627 (thanks to Eric Celeste, IMALPASS) 0.04 Wed Apr 15 09:22:59 2009 - Updated POD (thanks to Mr. Grue) 0.03 Sun Apr 05 13:22:21 2009 - param method for Net::Google::Spreadsheets::Row (thanks to Mr. Grue) 0.02 Sat Apr 04 22:32:40 2009 - Crypt::SSLeay dependency - Better error message on login failure (thanks to Mr. Grue) 0.01 Tue Dec 16 23:52:25 2008 - original version diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index 3ec0833..a96d6c6 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,351 +1,351 @@ package Net::Google::Spreadsheets; use Any::Moose; use Net::Google::DataAPI; use namespace::autoclean; use 5.008001; use Net::Google::AuthSub; use Net::Google::DataAPI::Auth::AuthSub; -our $VERSION = '0.10'; +our $VERSION = '0.11'; with 'Net::Google::DataAPI::Role::Service'; has gdata_version => ( is => 'ro', isa => 'Str', default => '3.0' ); has namespaces => ( is => 'ro', isa => 'HashRef', default => sub { { gs => 'http://schemas.google.com/spreadsheets/2006', gsx => 'http://schemas.google.com/spreadsheets/2006/extended', batch => 'http://schemas.google.com/gdata/batch', } }, ); has username => (is => 'ro', isa => 'Str'); has password => (is => 'ro', isa => 'Str'); has account_type => (is => 'ro', isa => 'Str', required => 1, default => 'HOSTED_OR_GOOGLE'); has source => (is => 'ro', isa => 'Str', required => 1, default => __PACKAGE__ . '-' . $VERSION); sub _build_auth { my ($self) = @_; my $authsub = Net::Google::AuthSub->new( source => $self->source, service => 'wise', account_type => $self->account_type, ); my $res = $authsub->login( $self->username, $self->password ); unless ($res && $res->is_success) { die 'Net::Google::AuthSub login failed'; } return Net::Google::DataAPI::Auth::AuthSub->new( authsub => $authsub, ); } feedurl spreadsheet => ( default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full', entry_class => 'Net::Google::Spreadsheets::Spreadsheet', can_add => 0, ); around spreadsheets => sub { my ($next, $self, $args) = @_; my @result = $next->($self, $args); if (my $key = $args->{key}) { @result = grep {$_->key eq $key} @result; } return @result; }; sub BUILD { my $self = shift; $self->auth; } __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, {row => 1, col => 4, input_value => 'age'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # fetch rows my @rows = $worksheet->rows; # or fetch rows with query @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); # delete the row $row->delete; # delete the worksheet $worksheet->delete; # create a table my $table = $spreadsheet->add_table( { worksheet => $new_worksheet, columns => ['name', 'nick', 'mail address', 'age'], } ); # add a record my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', 'mail address' => '[email protected]', age => '33', } ); # find a record my $found = $table->record( { sq => '"mail address" = "[email protected]"' } ); # delete it $found->delete; # delete table $table->delete; =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: -=over 4 +=over 2 -=item username +=item * username Username for Google. This should be full email address format like '[email protected]'. -=item password +=item * password Password corresponding to the username. -=item source +=item * source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: -=over 4 +=over 2 -=item title +=item * title title of the spreadsheet. -=item title-exact +=item * title-exact whether title search should match exactly or not. -=item key +=item * key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 AUTHORIZATIONS you can optionally pass auth object argument when initializing Net::Google::Spreadsheets instance. If you want to use AuthSub mechanism, make Net::Google::DataAPI::Auth::AuthSub object and path it to the constructor: my $authsub = Net::Google::AuthSub->new; $authsub->auth(undef, $session_token); my $service = Net::Google::Spreadsheet->new( auth => $authsub ); In OAuth case, like this: my $oauth = Net::Google::DataAPI::Auth::OAuth->new( consumer_key => 'consumer.example.com', consumer_secret => 'mys3cr3t', callback => 'http://consumer.example.com/callback', ); $oauth->get_request_token; my $url = $oauth->get_authorize_token_url; # show the url to the user and get the $verifier value $oauth->get_access_token({verifier => $verifier}); my $service = Net::Google::Spreadsheet->new( auth => $oauth ); =head1 TESTING To test this module, you have to prepare as below. -=over 4 +=over 2 -=item create a spreadsheet by hand +=item * create a spreadsheet by hand Go to L<http://docs.google.com> and create a spreadsheet. -=item set SPREADSHEET_TITLE environment variable +=item * set SPREADSHEET_TITLE environment variable export SPREADSHEET_TITLE='my test spreadsheet' or so. -=item set username and password for google.com via Config::Pit +=item * set username and password for google.com via Config::Pit install Config::Pit and type ppit set google.com then some editor comes up and type your username and password like --- username: [email protected] password: foobarbaz -=item run tests +=item * run tests as always, perl Makefile.PL make make test =back =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::DataAPI> L<Net::OAuth> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Record> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Net/Google/Spreadsheets/Record.pm b/lib/Net/Google/Spreadsheets/Record.pm index c1e4191..d4c6367 100644 --- a/lib/Net/Google/Spreadsheets/Record.pm +++ b/lib/Net/Google/Spreadsheets/Record.pm @@ -1,117 +1,124 @@ package Net::Google::Spreadsheets::Record; use Any::Moose; use namespace::autoclean; use XML::Atom::Util qw(nodelist); with 'Net::Google::DataAPI::Role::Entry', 'Net::Google::DataAPI::Role::HasContent'; after from_atom => sub { my ($self) = @_; for my $node (nodelist($self->elem, $self->ns('gs')->{uri}, 'field')) { $self->{content}->{$node->getAttribute('name')} = $node->textContent; } }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->{content}}) { $entry->add($self->ns('gs'), 'field', $value, {name => $key}); } return $entry; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Record - A representation class for Google Spreadsheet record. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a record my $record = $service->spreadsheet( { title => 'list for new year cards', } )->table( { title => 'addressbook', } )->record( { sq => 'id = 1000', } ); # get the content of a row my $hashref = $record->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $record->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $record->param('name'); # returns 'Nobuo Danjou' my $newval = $record->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new record value (with all fields) my $hashref2 = $record->param; # same as $record->content; + + # delete a record + $record->delete; =head1 METHODS =head2 param sets and gets content value. +=head2 delete + +deletes the record. + =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Row> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Row.pm b/lib/Net/Google/Spreadsheets/Row.pm index de14ab4..2103f90 100644 --- a/lib/Net/Google/Spreadsheets/Row.pm +++ b/lib/Net/Google/Spreadsheets/Row.pm @@ -1,155 +1,162 @@ package Net::Google::Spreadsheets::Row; use Any::Moose; use namespace::autoclean; use Net::Google::DataAPI; use XML::Atom::Util qw(nodelist); with 'Net::Google::DataAPI::Role::Entry', 'Net::Google::DataAPI::Role::HasContent'; after from_atom => sub { my ($self) = @_; for my $node (nodelist($self->elem, $self->ns('gsx')->{uri}, '*')) { $self->{content}->{$node->localname} = $node->textContent; } }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->{content}}) { $entry->set($self->ns('gsx'), $key, $value); } return $entry; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Row - A representation class for Google Spreadsheet row. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a row my $row = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->row( { sq => 'id = 1000' } ); # get the content of a row my $hashref = $row->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $row->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $row->param('name'); # returns 'Nobuo Danjou' my $newval = $row->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new row value (with all fields) my $hashref2 = $row->param; # same as $row->content; + # delete the row + $row->delete; + =head1 METHODS =head2 param sets and gets content value. +=head2 delete + +deletes the row. + =head1 CAVEATS Space characters in hash key of rows will be removed when you access rows. See below. my $ws = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'})->worksheet(1); $ws->batchupdate_cell( {col => 1,row => 1, input_value => 'name'}, {col => 2,row => 1, input_value => 'mail address'}, ); $ws->add_row( { name => 'my name', mailaddress => '[email protected]', # above passes, below fails. # 'mail address' => '[email protected]', } ); Instead, Net::Google::Spreadsheets::Table and Net::Google::Spreadsheets::Record allows space characters in column name. my $s = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'}); my $t = $s->add_table( { worksheet => $s->worksheet(1), columns => ['name', 'mail address'], } ); $t->add_record( { name => 'my name', 'mail address' => '[email protected]', } ); =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Spreadsheet.pm b/lib/Net/Google/Spreadsheets/Spreadsheet.pm index 9ea4b1d..a5587cb 100644 --- a/lib/Net/Google/Spreadsheets/Spreadsheet.pm +++ b/lib/Net/Google/Spreadsheets/Spreadsheet.pm @@ -1,234 +1,246 @@ package Net::Google::Spreadsheets::Spreadsheet; use Any::Moose; use namespace::autoclean; use Net::Google::DataAPI; with 'Net::Google::DataAPI::Role::Entry'; use URI; has title => ( is => 'ro', isa => 'Str', lazy_build => 1, ); entry_has key => ( isa => 'Str', is => 'ro', from_atom => sub { my ($self, $atom) = @_; my ($link) = grep { $_->rel eq 'alternate' && $_->type eq 'text/html' } $atom->link; return {URI->new($link->href)->query_form}->{key}; }, ); feedurl worksheet => ( entry_class => 'Net::Google::Spreadsheets::Worksheet', as_content_src => 1, ); feedurl table => ( entry_class => 'Net::Google::Spreadsheets::Table', rel => 'http://schemas.google.com/spreadsheets/2006#tablesfeed', ); __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Spreadsheet - Representation of spreadsheet. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # create a worksheet my $worksheet = $spreadsheet->add_worksheet( { title => 'foobar', col_count => 10, row_count => 100, } ); # list worksheets my @ws = $spreadsheet->worksheets; # find a worksheet my $ws = $spreadsheet->worksheet({title => 'fooba'}); # create a table my $table = $spreadsheet->add_table( { title => 'sample table', worksheet => $worksheet, columns => ['id', 'username', 'mail', 'password'], } ); # list tables my @t = $spreadsheet->tables; # find a worksheet my $t = $spreadsheet->table({title => 'sample table'}); =head1 METHODS =head2 worksheets(\%condition) Returns a list of Net::Google::Spreadsheets::Worksheet objects. Acceptable arguments are: -=over 4 +=over 2 -=item title +=item * title -=item title-exact +=item * title-exact =back =head2 worksheet(\%condition) Returns first item of worksheets(\%condition) if available. =head2 add_worksheet(\%attribuets) Creates new worksheet and returns a Net::Google::Spreadsheets::Worksheet object representing it. Arguments (all optional) are: -=over 4 +=over 2 -=item title +=item * title -=item col_count +=item * col_count -=item row_count +=item * row_count =back =head2 tables(\%condition) Returns a list of Net::Google::Spreadsheets::Table objects. Acceptable arguments are: -=over 4 +=over 2 -=item title +=item * title -=item title-exact +=item * title-exact =back =head2 table(\%condition) Returns first item of tables(\%condition) if available. =head2 add_table(\%attribuets) Creates new table and returns a Net::Google::Spreadsheets::Table object representing it. Arguments are: -=over 4 +=over 2 -=item title (optional) +=item * title (optional) -=item summary (optional) +=item * summary (optional) -=item worksheet +=item * worksheet Worksheet where the table lives. worksheet instance or the title. -=item header (optional, default = 1) +=item * header (optional, default = 1) Row number of header -=item start_row (optional, default = 2) +=item * start_row (optional, default = 2) The index of the first row of the data section. -=item insertion_mode (optional, default = 'overwrite') +=item * insertion_mode (optional, default = 'overwrite') Insertion mode. 'insert' inserts new row into the worksheet when creating record, 'overwrite' tries to use existing rows in the worksheet. -=item columns +=item * columns Columns of the table. you can specify them as hashref, arrayref, arrayref of hashref. $ss->add_table( { worksheet => $ws, columns => [ {index => 1, name => 'foo'}, {index => 2, name => 'bar'}, {index => 3, name => 'baz'}, ], } ); $ss->add_table( { worksheet => $ws, columns => { A => 'foo', B => 'bar', C => 'baz', } } ); $ss->add_table( { worksheet => $ws, columns => ['foo', 'bar', 'baz'], } ); 'index' of the first case and hash key of the second case is column index of the worksheet. In the third case, the columns is automatically placed to the columns of the worksheet from 'A' to 'Z' order. =back +=head1 DELETING A SPREADSHEET + +To delete a spreadsheet, use L<Net::Google::DocumentsList>. + + my $docs = Net::Google::DocumentsList->new( + username => '[email protected]', + password => 'mypassword' + ); + $docs->item({resource_id => 'spreadsheet:'. $ss->key})->delete; + =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Table> +L<Net::Google::DocumentsList> + =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Table.pm b/lib/Net/Google/Spreadsheets/Table.pm index 0f331a0..2402cac 100644 --- a/lib/Net/Google/Spreadsheets/Table.pm +++ b/lib/Net/Google/Spreadsheets/Table.pm @@ -1,228 +1,228 @@ package Net::Google::Spreadsheets::Table; use Any::Moose; use Any::Moose '::Util::TypeConstraints'; use namespace::autoclean; use Net::Google::DataAPI; use XML::Atom::Util qw(nodelist first create_element); with 'Net::Google::DataAPI::Role::Entry'; subtype 'ColumnList' => as 'ArrayRef[Net::Google::Spreadsheets::Table::Column]'; coerce 'ColumnList' => from 'ArrayRef[HashRef]' => via { [ map {Net::Google::Spreadsheets::Table::Column->new($_)} @$_ ] }; coerce 'ColumnList' => from 'ArrayRef[Str]' => via { my @c; my $index = 0; for my $value (@$_) { push @c, Net::Google::Spreadsheets::Table::Column->new( index => ++$index, name => $value, ); } \@c; }; coerce 'ColumnList' => from 'HashRef' => via { my @c; while (my ($key, $value) = each(%$_)) { push @c, Net::Google::Spreadsheets::Table::Column->new( index => $key, name => $value, ); } \@c; }; subtype 'WorksheetName' => as 'Str'; coerce 'WorksheetName' => from 'Net::Google::Spreadsheets::Worksheet' => via { $_->title }; feedurl record => ( entry_class => 'Net::Google::Spreadsheets::Record', arg_builder => sub { my ($self, $args) = @_; return {content => $args}; }, as_content_src => 1, ); has summary => ( is => 'rw', isa => 'Str' ); has worksheet => ( is => 'ro', isa => 'WorksheetName', coerce => 1 ); has header => ( is => 'ro', isa => 'Int', required => 1, default => 1 ); has start_row => ( is => 'ro', isa => 'Int', required => 1, default => 2 ); has num_rows => ( is => 'ro', isa => 'Int' ); has columns => ( is => 'ro', isa => 'ColumnList', coerce => 1 ); has insertion_mode => ( is => 'ro', isa => (enum ['insert', 'overwrite']), default => 'overwrite' ); after from_atom => sub { my ($self) = @_; my $gsns = $self->ns('gs')->{uri}; my $elem = $self->elem; $self->{summary} = $self->atom->summary; $self->{worksheet} = first( $elem, $gsns, 'worksheet')->getAttribute('name'); $self->{header} = first( $elem, $gsns, 'header')->getAttribute('row'); my @columns; my $data = first($elem, $gsns, 'data'); $self->{insertion_mode} = $data->getAttribute('insertionMode'); $self->{start_row} = $data->getAttribute('startRow'); $self->{num_rows} = $data->getAttribute('numRows'); for (nodelist($data, $gsns, 'column')) { push @columns, Net::Google::Spreadsheets::Table::Column->new( index => $_->getAttribute('index'), name => $_->getAttribute('name'), ); } $self->{columns} = \@columns; }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); my $gsns = $self->ns('gs')->{uri}; $entry->summary($self->summary) if $self->summary; $entry->set($gsns, 'worksheet', '', {name => $self->worksheet}); $entry->set($gsns, 'header', '', {row => $self->header}); my $data = create_element($gsns, 'data'); $data->setAttribute(startRow => $self->start_row); $data->setAttribute(insertionMode => $self->insertion_mode); $data->setAttribute(startRow => $self->start_row) if $self->start_row; for ( @{$self->columns} ) { my $column = create_element($gsns, 'column'); $column->setAttribute(index => $_->index); $column->setAttribute(name => $_->name); $data->appendChild($column); } $entry->set($gsns, 'data', $data); return $entry; }; __PACKAGE__->meta->make_immutable; package # hide from PAUSE Net::Google::Spreadsheets::Table::Column; use Any::Moose; has 'index' => ( is => 'ro', isa => 'Str' ); has 'name' => ( is => 'ro', isa => 'Str' ); __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Table - A representation class for Google Spreadsheet table. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a table my $table = $service->spreadsheet( { title => 'list for new year cards', } )->table( { title => 'sample table', } ); # create a record my $r = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # get records my @records = $table->records; # search records @records = $table->records({sq => 'age > 20'}); # search a record my $record = $table->record({sq => 'name = "Nobuo Danjou"'}); =head1 METHODS =head2 records(\%condition) Returns a list of Net::Google::Spreadsheets::Record objects. Acceptable arguments are: -=over 4 +=over 2 -=item sq +=item * sq Structured query on the full text in the worksheet. see the URL below for detail. -=item orderby +=item * orderby Set column name to use for ordering. -=item reverse +=item * reverse Set 'true' or 'false'. The default is 'false'. =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#RecordParameters> for details. =head2 record(\%condition) Returns first item of records(\%condition) if available. =head2 add_record(\%contents) Creates new record and returns a Net::Google::Spreadsheets::Record object representing it. Arguments are contents of a row as a hashref. my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Record> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Worksheet.pm b/lib/Net/Google/Spreadsheets/Worksheet.pm index 262ac58..7def528 100644 --- a/lib/Net/Google/Spreadsheets/Worksheet.pm +++ b/lib/Net/Google/Spreadsheets/Worksheet.pm @@ -1,247 +1,257 @@ package Net::Google::Spreadsheets::Worksheet; use Any::Moose; use namespace::autoclean; use Net::Google::DataAPI; with 'Net::Google::DataAPI::Role::Entry'; use Carp; use Net::Google::Spreadsheets::Cell; use XML::Atom::Util qw(first); feedurl row => ( entry_class => 'Net::Google::Spreadsheets::Row', as_content_src => 1, arg_builder => sub { my ($self, $args) = @_; return {content => $args}; }, ); feedurl cell => ( entry_class => 'Net::Google::Spreadsheets::Cell', can_add => 0, rel => 'http://schemas.google.com/spreadsheets/2006#cellsfeed', query_builder => sub { my ($self, $args) = @_; if (my $col = delete $args->{col}) { $args->{'max-col'} = $col; $args->{'min-col'} = $col; $args->{'return-empty'} = 'true'; } if (my $row = delete $args->{row}) { $args->{'max-row'} = $row; $args->{'min-row'} = $row; $args->{'return-empty'} = 'true'; } return $args; }, ); entry_has row_count => ( isa => 'Int', is => 'rw', default => 100, tagname => 'rowCount', ns => 'gs', ); entry_has col_count => ( isa => 'Int', is => 'rw', default => 20, tagname => 'colCount', ns => 'gs', ); __PACKAGE__->meta->make_immutable; sub batchupdate_cell { my ($self, @args) = @_; my $feed = XML::Atom::Feed->new; for ( @args ) { my $id = sprintf("%s/R%sC%s",$self->cell_feedurl, $_->{row}, $_->{col}); $_->{id} = $_->{editurl} = $id; $_->{container} = $self, my $entry = Net::Google::Spreadsheets::Cell->new($_)->to_atom; $entry->set($self->ns('batch'), operation => '', {type => 'update'}); $entry->set($self->ns('batch'), id => $id); $feed->add_entry($entry); } my $res_feed = $self->service->post( $self->cell_feedurl."/batch", $feed, {'If-Match' => '*'} ); $self->sync; return map { Net::Google::Spreadsheets::Cell->new( atom => $_, container => $self, ) } grep { my $node = first( $_->elem, $self->ns('batch')->{uri}, 'status' ); $node->getAttribute('code') == 200; } $res_feed->entries; } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Worksheet - Representation of worksheet. =head1 SYNOPSIS my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); my $ss = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); my $worksheet = $ss->worksheet({title => 'Sheet1'}); # update cell by batch request $worksheet->batchupdate_cell( {col => 1, row => 1, input_value => 'name'}, {col => 2, row => 1, input_value => 'nick'}, {col => 3, row => 1, input_value => 'mail'}, {col => 4, row => 1, input_value => 'age'}, ); # get a cell object my $cell = $worksheet->cell({col => 1, row => 1}); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # get rows my @rows = $worksheet->rows; # search rows @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); + # delete the worksheet + # Note that this will fail if the worksheet is the only one + # within the spreadsheet. + + $worksheet->delete; + =head1 METHODS =head2 rows(\%condition) Returns a list of Net::Google::Spreadsheets::Row objects. Acceptable arguments are: -=over 4 +=over 2 -=item sq +=item * sq Structured query on the full text in the worksheet. see the URL below for detail. -=item orderby +=item * orderby Set column name to use for ordering. -=item reverse +=item * reverse Set 'true' or 'false'. The default is 'false'. =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#ListParameters> for details. =head2 row(\%condition) Returns first item of rows(\%condition) if available. =head2 add_row(\%contents) Creates new row and returns a Net::Google::Spreadsheets::Row object representing it. Arguments are contents of a row as a hashref. my $row = $ws->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); =head2 cells(\%args) Returns a list of Net::Google::Spreadsheets::Cell objects. Acceptable arguments are: -=over 4 +=over 2 -=item min-row +=item * min-row -=item max-row +=item * max-row -=item min-col +=item * min-col -=item max-col +=item * max-col -=item range +=item * range -=item return-empty +=item * return-empty =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#CellParameters> for details. =head2 cell(\%args) Returns Net::Google::Spreadsheets::Cell object. Arguments are: -=over 4 +=over 2 -=item col +=item * col -=item row +=item * row =back =head2 batchupdate_cell(@args) update multiple cells with a batch request. Pass a list of hash references containing: -=over 4 +=over 2 -=item col +=item * col -=item row +=item * row -=item input_value +=item * input_value =back +=head2 delete + +Deletes the worksheet. Note that this will fail if the worksheet is only one within the spreadsheet. + =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut
lopnor/Net-Google-Spreadsheets
a5d829e53d121d211bf9bf032954c7456d3a15c1
Checking in changes prior to tagging of version 0.10. Changelog diff is:
diff --git a/Changes b/Changes index 8d5475b..a177220 100644 --- a/Changes +++ b/Changes @@ -1,38 +1,41 @@ Revision history for Perl extension Net::Google::Spreadsheets +0.10 Mon Mar 15 23:49:00 2010 + - update dependencies (Mouse 0.51, Net::Google::DataAPI 0.17) + 0.09 Sun Mar 07 23:27:00 2010 - Fix spreadsheet key changes (thanks to Colin Magee) 0.08 Thu Dec 31 19:20:30 2009 - follow Net::Google::DataAPI changes - update POD 0.07 Fri Dec 22 22:53:34 2009 - now uses Net::Google::DataAPI - AuthSub and OAuth support via Net::Google::DataAPI - now uses Any::Moose 0.06 Thu Aug 20 23:21:35 2009 - Refactored internals 0.06_01 Mon Arg 16 16:01:27 2009 - Supports Google Spreadsheets API version 3.0 - Add table and record feeds supports - Better error handlings (no more redirects, captures xml parse error, and more) - Refactored internals 0.05 Sun Aug 15 09:47:50 2009 - Fix Moose attribute problem #48627 (thanks to Eric Celeste, IMALPASS) 0.04 Wed Apr 15 09:22:59 2009 - Updated POD (thanks to Mr. Grue) 0.03 Sun Apr 05 13:22:21 2009 - param method for Net::Google::Spreadsheets::Row (thanks to Mr. Grue) 0.02 Sat Apr 04 22:32:40 2009 - Crypt::SSLeay dependency - Better error message on login failure (thanks to Mr. Grue) 0.01 Tue Dec 16 23:52:25 2008 - original version diff --git a/Makefile.PL b/Makefile.PL index 111f284..764b721 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,26 +1,26 @@ use inc::Module::Install; name 'Net-Google-Spreadsheets'; all_from 'lib/Net/Google/Spreadsheets.pm'; requires 'Carp'; requires 'XML::Atom'; requires 'Net::Google::AuthSub'; -requires 'Net::Google::DataAPI' => '0.11'; +requires 'Net::Google::DataAPI' => '0.17'; requires 'URI'; requires 'namespace::autoclean'; requires_any_moose( moose => '0.56', - mouse => '0.40', + mouse => '0.51', ); tests_recursive; author_tests 'xt'; build_requires 'Test::More' => '0.88'; build_requires 'Test::Exception'; build_requires 'Test::MockModule'; build_requires 'Test::MockObject'; use_test_base; auto_include; auto_set_repository; WriteAll; diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index e516b5a..3ec0833 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,351 +1,351 @@ package Net::Google::Spreadsheets; use Any::Moose; use Net::Google::DataAPI; use namespace::autoclean; use 5.008001; use Net::Google::AuthSub; use Net::Google::DataAPI::Auth::AuthSub; -our $VERSION = '0.09'; +our $VERSION = '0.10'; with 'Net::Google::DataAPI::Role::Service'; has gdata_version => ( is => 'ro', isa => 'Str', default => '3.0' ); has namespaces => ( is => 'ro', isa => 'HashRef', default => sub { { gs => 'http://schemas.google.com/spreadsheets/2006', gsx => 'http://schemas.google.com/spreadsheets/2006/extended', batch => 'http://schemas.google.com/gdata/batch', } }, ); has username => (is => 'ro', isa => 'Str'); has password => (is => 'ro', isa => 'Str'); has account_type => (is => 'ro', isa => 'Str', required => 1, default => 'HOSTED_OR_GOOGLE'); has source => (is => 'ro', isa => 'Str', required => 1, default => __PACKAGE__ . '-' . $VERSION); sub _build_auth { my ($self) = @_; my $authsub = Net::Google::AuthSub->new( source => $self->source, service => 'wise', account_type => $self->account_type, ); my $res = $authsub->login( $self->username, $self->password ); unless ($res && $res->is_success) { die 'Net::Google::AuthSub login failed'; } return Net::Google::DataAPI::Auth::AuthSub->new( authsub => $authsub, ); } feedurl spreadsheet => ( default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full', entry_class => 'Net::Google::Spreadsheets::Spreadsheet', can_add => 0, ); around spreadsheets => sub { my ($next, $self, $args) = @_; my @result = $next->($self, $args); if (my $key = $args->{key}) { @result = grep {$_->key eq $key} @result; } return @result; }; sub BUILD { my $self = shift; $self->auth; } __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, {row => 1, col => 4, input_value => 'age'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # fetch rows my @rows = $worksheet->rows; # or fetch rows with query @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); # delete the row $row->delete; # delete the worksheet $worksheet->delete; # create a table my $table = $spreadsheet->add_table( { worksheet => $new_worksheet, columns => ['name', 'nick', 'mail address', 'age'], } ); # add a record my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', 'mail address' => '[email protected]', age => '33', } ); # find a record my $found = $table->record( { sq => '"mail address" = "[email protected]"' } ); # delete it $found->delete; # delete table $table->delete; =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 4 =item username Username for Google. This should be full email address format like '[email protected]'. =item password Password corresponding to the username. =item source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 4 =item title title of the spreadsheet. =item title-exact whether title search should match exactly or not. =item key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 AUTHORIZATIONS you can optionally pass auth object argument when initializing Net::Google::Spreadsheets instance. If you want to use AuthSub mechanism, make Net::Google::DataAPI::Auth::AuthSub object and path it to the constructor: my $authsub = Net::Google::AuthSub->new; $authsub->auth(undef, $session_token); my $service = Net::Google::Spreadsheet->new( auth => $authsub ); In OAuth case, like this: my $oauth = Net::Google::DataAPI::Auth::OAuth->new( consumer_key => 'consumer.example.com', consumer_secret => 'mys3cr3t', callback => 'http://consumer.example.com/callback', ); $oauth->get_request_token; my $url = $oauth->get_authorize_token_url; # show the url to the user and get the $verifier value $oauth->get_access_token({verifier => $verifier}); my $service = Net::Google::Spreadsheet->new( auth => $oauth ); =head1 TESTING To test this module, you have to prepare as below. =over 4 =item create a spreadsheet by hand Go to L<http://docs.google.com> and create a spreadsheet. =item set SPREADSHEET_TITLE environment variable export SPREADSHEET_TITLE='my test spreadsheet' or so. =item set username and password for google.com via Config::Pit install Config::Pit and type ppit set google.com then some editor comes up and type your username and password like --- username: [email protected] password: foobarbaz =item run tests as always, perl Makefile.PL make make test =back =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::DataAPI> L<Net::OAuth> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Record> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
lopnor/Net-Google-Spreadsheets
eb9e6202aeef9cdf11db1c993668bf7fb6076204
Checking in changes prior to tagging of version 0.09. Changelog diff is:
diff --git a/Changes b/Changes index da1c3ca..8d5475b 100644 --- a/Changes +++ b/Changes @@ -1,35 +1,38 @@ Revision history for Perl extension Net::Google::Spreadsheets +0.09 Sun Mar 07 23:27:00 2010 + - Fix spreadsheet key changes (thanks to Colin Magee) + 0.08 Thu Dec 31 19:20:30 2009 - follow Net::Google::DataAPI changes - update POD 0.07 Fri Dec 22 22:53:34 2009 - now uses Net::Google::DataAPI - AuthSub and OAuth support via Net::Google::DataAPI - now uses Any::Moose 0.06 Thu Aug 20 23:21:35 2009 - Refactored internals 0.06_01 Mon Arg 16 16:01:27 2009 - Supports Google Spreadsheets API version 3.0 - Add table and record feeds supports - Better error handlings (no more redirects, captures xml parse error, and more) - Refactored internals 0.05 Sun Aug 15 09:47:50 2009 - Fix Moose attribute problem #48627 (thanks to Eric Celeste, IMALPASS) 0.04 Wed Apr 15 09:22:59 2009 - Updated POD (thanks to Mr. Grue) 0.03 Sun Apr 05 13:22:21 2009 - param method for Net::Google::Spreadsheets::Row (thanks to Mr. Grue) 0.02 Sat Apr 04 22:32:40 2009 - Crypt::SSLeay dependency - Better error message on login failure (thanks to Mr. Grue) 0.01 Tue Dec 16 23:52:25 2008 - original version diff --git a/Makefile.PL b/Makefile.PL index 72ad51e..111f284 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,27 +1,26 @@ use inc::Module::Install; name 'Net-Google-Spreadsheets'; all_from 'lib/Net/Google/Spreadsheets.pm'; requires 'Carp'; requires 'XML::Atom'; requires 'Net::Google::AuthSub'; requires 'Net::Google::DataAPI' => '0.11'; requires 'URI'; -requires 'Path::Class'; requires 'namespace::autoclean'; requires_any_moose( moose => '0.56', mouse => '0.40', ); tests_recursive; author_tests 'xt'; build_requires 'Test::More' => '0.88'; build_requires 'Test::Exception'; build_requires 'Test::MockModule'; build_requires 'Test::MockObject'; use_test_base; auto_include; auto_set_repository; WriteAll; diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index e890299..e516b5a 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,351 +1,351 @@ package Net::Google::Spreadsheets; use Any::Moose; use Net::Google::DataAPI; use namespace::autoclean; use 5.008001; use Net::Google::AuthSub; use Net::Google::DataAPI::Auth::AuthSub; -our $VERSION = '0.08'; +our $VERSION = '0.09'; with 'Net::Google::DataAPI::Role::Service'; has gdata_version => ( is => 'ro', isa => 'Str', default => '3.0' ); has namespaces => ( is => 'ro', isa => 'HashRef', default => sub { { gs => 'http://schemas.google.com/spreadsheets/2006', gsx => 'http://schemas.google.com/spreadsheets/2006/extended', batch => 'http://schemas.google.com/gdata/batch', } }, ); has username => (is => 'ro', isa => 'Str'); has password => (is => 'ro', isa => 'Str'); has account_type => (is => 'ro', isa => 'Str', required => 1, default => 'HOSTED_OR_GOOGLE'); has source => (is => 'ro', isa => 'Str', required => 1, default => __PACKAGE__ . '-' . $VERSION); sub _build_auth { my ($self) = @_; my $authsub = Net::Google::AuthSub->new( source => $self->source, service => 'wise', account_type => $self->account_type, ); my $res = $authsub->login( $self->username, $self->password ); unless ($res && $res->is_success) { die 'Net::Google::AuthSub login failed'; } return Net::Google::DataAPI::Auth::AuthSub->new( authsub => $authsub, ); } feedurl spreadsheet => ( default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full', entry_class => 'Net::Google::Spreadsheets::Spreadsheet', can_add => 0, ); around spreadsheets => sub { my ($next, $self, $args) = @_; my @result = $next->($self, $args); if (my $key = $args->{key}) { @result = grep {$_->key eq $key} @result; } return @result; }; sub BUILD { my $self = shift; $self->auth; } __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, {row => 1, col => 4, input_value => 'age'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # fetch rows my @rows = $worksheet->rows; # or fetch rows with query @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); # delete the row $row->delete; # delete the worksheet $worksheet->delete; # create a table my $table = $spreadsheet->add_table( { worksheet => $new_worksheet, columns => ['name', 'nick', 'mail address', 'age'], } ); # add a record my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', 'mail address' => '[email protected]', age => '33', } ); # find a record my $found = $table->record( { sq => '"mail address" = "[email protected]"' } ); # delete it $found->delete; # delete table $table->delete; =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 4 =item username Username for Google. This should be full email address format like '[email protected]'. =item password Password corresponding to the username. =item source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 4 =item title title of the spreadsheet. =item title-exact whether title search should match exactly or not. =item key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 AUTHORIZATIONS you can optionally pass auth object argument when initializing Net::Google::Spreadsheets instance. If you want to use AuthSub mechanism, make Net::Google::DataAPI::Auth::AuthSub object and path it to the constructor: my $authsub = Net::Google::AuthSub->new; $authsub->auth(undef, $session_token); my $service = Net::Google::Spreadsheet->new( auth => $authsub ); In OAuth case, like this: my $oauth = Net::Google::DataAPI::Auth::OAuth->new( consumer_key => 'consumer.example.com', consumer_secret => 'mys3cr3t', callback => 'http://consumer.example.com/callback', ); $oauth->get_request_token; my $url = $oauth->get_authorize_token_url; # show the url to the user and get the $verifier value $oauth->get_access_token({verifier => $verifier}); my $service = Net::Google::Spreadsheet->new( auth => $oauth ); =head1 TESTING To test this module, you have to prepare as below. =over 4 =item create a spreadsheet by hand Go to L<http://docs.google.com> and create a spreadsheet. =item set SPREADSHEET_TITLE environment variable export SPREADSHEET_TITLE='my test spreadsheet' or so. =item set username and password for google.com via Config::Pit install Config::Pit and type ppit set google.com then some editor comes up and type your username and password like --- username: [email protected] password: foobarbaz =item run tests as always, perl Makefile.PL make make test =back =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::DataAPI> L<Net::OAuth> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Record> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Net/Google/Spreadsheets/Spreadsheet.pm b/lib/Net/Google/Spreadsheets/Spreadsheet.pm index 06b8cdc..9ea4b1d 100644 --- a/lib/Net/Google/Spreadsheets/Spreadsheet.pm +++ b/lib/Net/Google/Spreadsheets/Spreadsheet.pm @@ -1,232 +1,234 @@ package Net::Google::Spreadsheets::Spreadsheet; use Any::Moose; use namespace::autoclean; use Net::Google::DataAPI; with 'Net::Google::DataAPI::Role::Entry'; -use Path::Class; use URI; has title => ( is => 'ro', isa => 'Str', lazy_build => 1, ); entry_has key => ( isa => 'Str', is => 'ro', from_atom => sub { my ($self, $atom) = @_; - return file(URI->new($self->id)->path)->basename; + my ($link) = grep { + $_->rel eq 'alternate' && $_->type eq 'text/html' + } $atom->link; + return {URI->new($link->href)->query_form}->{key}; }, ); feedurl worksheet => ( entry_class => 'Net::Google::Spreadsheets::Worksheet', as_content_src => 1, ); feedurl table => ( entry_class => 'Net::Google::Spreadsheets::Table', rel => 'http://schemas.google.com/spreadsheets/2006#tablesfeed', ); __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Spreadsheet - Representation of spreadsheet. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # create a worksheet my $worksheet = $spreadsheet->add_worksheet( { title => 'foobar', col_count => 10, row_count => 100, } ); # list worksheets my @ws = $spreadsheet->worksheets; # find a worksheet my $ws = $spreadsheet->worksheet({title => 'fooba'}); # create a table my $table = $spreadsheet->add_table( { title => 'sample table', worksheet => $worksheet, columns => ['id', 'username', 'mail', 'password'], } ); # list tables my @t = $spreadsheet->tables; # find a worksheet my $t = $spreadsheet->table({title => 'sample table'}); =head1 METHODS =head2 worksheets(\%condition) Returns a list of Net::Google::Spreadsheets::Worksheet objects. Acceptable arguments are: =over 4 =item title =item title-exact =back =head2 worksheet(\%condition) Returns first item of worksheets(\%condition) if available. =head2 add_worksheet(\%attribuets) Creates new worksheet and returns a Net::Google::Spreadsheets::Worksheet object representing it. Arguments (all optional) are: =over 4 =item title =item col_count =item row_count =back =head2 tables(\%condition) Returns a list of Net::Google::Spreadsheets::Table objects. Acceptable arguments are: =over 4 =item title =item title-exact =back =head2 table(\%condition) Returns first item of tables(\%condition) if available. =head2 add_table(\%attribuets) Creates new table and returns a Net::Google::Spreadsheets::Table object representing it. Arguments are: =over 4 =item title (optional) =item summary (optional) =item worksheet Worksheet where the table lives. worksheet instance or the title. =item header (optional, default = 1) Row number of header =item start_row (optional, default = 2) The index of the first row of the data section. =item insertion_mode (optional, default = 'overwrite') Insertion mode. 'insert' inserts new row into the worksheet when creating record, 'overwrite' tries to use existing rows in the worksheet. =item columns Columns of the table. you can specify them as hashref, arrayref, arrayref of hashref. $ss->add_table( { worksheet => $ws, columns => [ {index => 1, name => 'foo'}, {index => 2, name => 'bar'}, {index => 3, name => 'baz'}, ], } ); $ss->add_table( { worksheet => $ws, columns => { A => 'foo', B => 'bar', C => 'baz', } } ); $ss->add_table( { worksheet => $ws, columns => ['foo', 'bar', 'baz'], } ); 'index' of the first case and hash key of the second case is column index of the worksheet. In the third case, the columns is automatically placed to the columns of the worksheet from 'A' to 'Z' order. =back =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Table> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut
lopnor/Net-Google-Spreadsheets
8e30ea1bb0b7f4d6c0fd1250272a892b6dd69534
Checking in changes prior to tagging of version 0.08. Changelog diff is:
diff --git a/Changes b/Changes index 9c15f58..da1c3ca 100644 --- a/Changes +++ b/Changes @@ -1,31 +1,35 @@ Revision history for Perl extension Net::Google::Spreadsheets +0.08 Thu Dec 31 19:20:30 2009 + - follow Net::Google::DataAPI changes + - update POD + 0.07 Fri Dec 22 22:53:34 2009 - now uses Net::Google::DataAPI - AuthSub and OAuth support via Net::Google::DataAPI - now uses Any::Moose 0.06 Thu Aug 20 23:21:35 2009 - Refactored internals 0.06_01 Mon Arg 16 16:01:27 2009 - Supports Google Spreadsheets API version 3.0 - Add table and record feeds supports - Better error handlings (no more redirects, captures xml parse error, and more) - Refactored internals 0.05 Sun Aug 15 09:47:50 2009 - Fix Moose attribute problem #48627 (thanks to Eric Celeste, IMALPASS) 0.04 Wed Apr 15 09:22:59 2009 - Updated POD (thanks to Mr. Grue) 0.03 Sun Apr 05 13:22:21 2009 - param method for Net::Google::Spreadsheets::Row (thanks to Mr. Grue) 0.02 Sat Apr 04 22:32:40 2009 - Crypt::SSLeay dependency - Better error message on login failure (thanks to Mr. Grue) 0.01 Tue Dec 16 23:52:25 2008 - original version diff --git a/Makefile.PL b/Makefile.PL index 824d043..72ad51e 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,27 +1,27 @@ use inc::Module::Install; name 'Net-Google-Spreadsheets'; all_from 'lib/Net/Google/Spreadsheets.pm'; requires 'Carp'; requires 'XML::Atom'; requires 'Net::Google::AuthSub'; -requires 'Net::Google::DataAPI' => '0.09'; +requires 'Net::Google::DataAPI' => '0.11'; requires 'URI'; requires 'Path::Class'; requires 'namespace::autoclean'; requires_any_moose( moose => '0.56', mouse => '0.40', ); tests_recursive; author_tests 'xt'; build_requires 'Test::More' => '0.88'; build_requires 'Test::Exception'; build_requires 'Test::MockModule'; build_requires 'Test::MockObject'; use_test_base; auto_include; auto_set_repository; WriteAll; diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index 114af3a..e890299 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,348 +1,351 @@ package Net::Google::Spreadsheets; use Any::Moose; use Net::Google::DataAPI; use namespace::autoclean; use 5.008001; use Net::Google::AuthSub; use Net::Google::DataAPI::Auth::AuthSub; -our $VERSION = '0.07'; +our $VERSION = '0.08'; with 'Net::Google::DataAPI::Role::Service'; -has '+gdata_version' => (default => '3.0'); -has '+namespaces' => ( +has gdata_version => ( + is => 'ro', + isa => 'Str', + default => '3.0' +); +has namespaces => ( + is => 'ro', + isa => 'HashRef', default => sub { { gs => 'http://schemas.google.com/spreadsheets/2006', gsx => 'http://schemas.google.com/spreadsheets/2006/extended', batch => 'http://schemas.google.com/gdata/batch', } }, ); has username => (is => 'ro', isa => 'Str'); has password => (is => 'ro', isa => 'Str'); has account_type => (is => 'ro', isa => 'Str', required => 1, default => 'HOSTED_OR_GOOGLE'); has source => (is => 'ro', isa => 'Str', required => 1, default => __PACKAGE__ . '-' . $VERSION); sub _build_auth { my ($self) = @_; my $authsub = Net::Google::AuthSub->new( source => $self->source, service => 'wise', account_type => $self->account_type, ); my $res = $authsub->login( $self->username, $self->password ); unless ($res && $res->is_success) { die 'Net::Google::AuthSub login failed'; } return Net::Google::DataAPI::Auth::AuthSub->new( authsub => $authsub, ); } feedurl spreadsheet => ( default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full', entry_class => 'Net::Google::Spreadsheets::Spreadsheet', can_add => 0, ); around spreadsheets => sub { my ($next, $self, $args) = @_; my @result = $next->($self, $args); if (my $key = $args->{key}) { @result = grep {$_->key eq $key} @result; } return @result; }; sub BUILD { my $self = shift; $self->auth; } __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, {row => 1, col => 4, input_value => 'age'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # fetch rows my @rows = $worksheet->rows; # or fetch rows with query @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); # delete the row $row->delete; # delete the worksheet $worksheet->delete; # create a table my $table = $spreadsheet->add_table( { worksheet => $new_worksheet, columns => ['name', 'nick', 'mail address', 'age'], } ); # add a record my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', 'mail address' => '[email protected]', age => '33', } ); # find a record my $found = $table->record( { sq => '"mail address" = "[email protected]"' } ); # delete it $found->delete; # delete table $table->delete; =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 4 =item username Username for Google. This should be full email address format like '[email protected]'. =item password Password corresponding to the username. =item source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 4 =item title title of the spreadsheet. =item title-exact whether title search should match exactly or not. =item key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 AUTHORIZATIONS you can optionally pass auth object argument when initializing Net::Google::Spreadsheets instance. If you want to use AuthSub mechanism, make Net::Google::DataAPI::Auth::AuthSub object and path it to the constructor: my $authsub = Net::Google::AuthSub->new; $authsub->auth(undef, $session_token); - my $auth = Net::Google::DataAPI::Auth::AuthSub->new( - authsub => $authsub - ); my $service = Net::Google::Spreadsheet->new( - auth => $auth + auth => $authsub ); In OAuth case, like this: my $oauth = Net::Google::DataAPI::Auth::OAuth->new( consumer_key => 'consumer.example.com', consumer_secret => 'mys3cr3t', callback => 'http://consumer.example.com/callback', ); $oauth->get_request_token; my $url = $oauth->get_authorize_token_url; # show the url to the user and get the $verifier value $oauth->get_access_token({verifier => $verifier}); my $service = Net::Google::Spreadsheet->new( auth => $oauth ); =head1 TESTING To test this module, you have to prepare as below. =over 4 =item create a spreadsheet by hand Go to L<http://docs.google.com> and create a spreadsheet. =item set SPREADSHEET_TITLE environment variable export SPREADSHEET_TITLE='my test spreadsheet' or so. =item set username and password for google.com via Config::Pit install Config::Pit and type ppit set google.com then some editor comes up and type your username and password like --- username: [email protected] password: foobarbaz =item run tests as always, perl Makefile.PL make make test =back =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::DataAPI> L<Net::OAuth> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Record> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
lopnor/Net-Google-Spreadsheets
57e600245ce55b36443963a0592e52282e9be18f
follow Net::Google::DataAPI changes
diff --git a/lib/Net/Google/Spreadsheets/Spreadsheet.pm b/lib/Net/Google/Spreadsheets/Spreadsheet.pm index 9b1db57..06b8cdc 100644 --- a/lib/Net/Google/Spreadsheets/Spreadsheet.pm +++ b/lib/Net/Google/Spreadsheets/Spreadsheet.pm @@ -1,230 +1,232 @@ package Net::Google::Spreadsheets::Spreadsheet; use Any::Moose; use namespace::autoclean; use Net::Google::DataAPI; with 'Net::Google::DataAPI::Role::Entry'; use Path::Class; use URI; has title => ( is => 'ro', + isa => 'Str', + lazy_build => 1, ); entry_has key => ( isa => 'Str', is => 'ro', from_atom => sub { my ($self, $atom) = @_; return file(URI->new($self->id)->path)->basename; }, ); feedurl worksheet => ( entry_class => 'Net::Google::Spreadsheets::Worksheet', as_content_src => 1, ); feedurl table => ( entry_class => 'Net::Google::Spreadsheets::Table', rel => 'http://schemas.google.com/spreadsheets/2006#tablesfeed', ); __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Spreadsheet - Representation of spreadsheet. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # create a worksheet my $worksheet = $spreadsheet->add_worksheet( { title => 'foobar', col_count => 10, row_count => 100, } ); # list worksheets my @ws = $spreadsheet->worksheets; # find a worksheet my $ws = $spreadsheet->worksheet({title => 'fooba'}); # create a table my $table = $spreadsheet->add_table( { title => 'sample table', worksheet => $worksheet, columns => ['id', 'username', 'mail', 'password'], } ); # list tables my @t = $spreadsheet->tables; # find a worksheet my $t = $spreadsheet->table({title => 'sample table'}); =head1 METHODS =head2 worksheets(\%condition) Returns a list of Net::Google::Spreadsheets::Worksheet objects. Acceptable arguments are: =over 4 =item title =item title-exact =back =head2 worksheet(\%condition) Returns first item of worksheets(\%condition) if available. =head2 add_worksheet(\%attribuets) Creates new worksheet and returns a Net::Google::Spreadsheets::Worksheet object representing it. Arguments (all optional) are: =over 4 =item title =item col_count =item row_count =back =head2 tables(\%condition) Returns a list of Net::Google::Spreadsheets::Table objects. Acceptable arguments are: =over 4 =item title =item title-exact =back =head2 table(\%condition) Returns first item of tables(\%condition) if available. =head2 add_table(\%attribuets) Creates new table and returns a Net::Google::Spreadsheets::Table object representing it. Arguments are: =over 4 =item title (optional) =item summary (optional) =item worksheet Worksheet where the table lives. worksheet instance or the title. =item header (optional, default = 1) Row number of header =item start_row (optional, default = 2) The index of the first row of the data section. =item insertion_mode (optional, default = 'overwrite') Insertion mode. 'insert' inserts new row into the worksheet when creating record, 'overwrite' tries to use existing rows in the worksheet. =item columns Columns of the table. you can specify them as hashref, arrayref, arrayref of hashref. $ss->add_table( { worksheet => $ws, columns => [ {index => 1, name => 'foo'}, {index => 2, name => 'bar'}, {index => 3, name => 'baz'}, ], } ); $ss->add_table( { worksheet => $ws, columns => { A => 'foo', B => 'bar', C => 'baz', } } ); $ss->add_table( { worksheet => $ws, columns => ['foo', 'bar', 'baz'], } ); 'index' of the first case and hash key of the second case is column index of the worksheet. In the third case, the columns is automatically placed to the columns of the worksheet from 'A' to 'Z' order. =back =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Table> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut
lopnor/Net-Google-Spreadsheets
935e990c3a59b0a2be0daf4de52b90ee58823336
Checking in changes prior to tagging of version 0.07. Changelog diff is:
diff --git a/Changes b/Changes index 6f67c25..9c15f58 100644 --- a/Changes +++ b/Changes @@ -1,29 +1,31 @@ Revision history for Perl extension Net::Google::Spreadsheets -0.07 Tue Sep 22 18:11:09 2009 - - Use Net::Google::DataAPI +0.07 Fri Dec 22 22:53:34 2009 + - now uses Net::Google::DataAPI + - AuthSub and OAuth support via Net::Google::DataAPI + - now uses Any::Moose 0.06 Thu Aug 20 23:21:35 2009 - Refactored internals 0.06_01 Mon Arg 16 16:01:27 2009 - Supports Google Spreadsheets API version 3.0 - Add table and record feeds supports - Better error handlings (no more redirects, captures xml parse error, and more) - Refactored internals 0.05 Sun Aug 15 09:47:50 2009 - Fix Moose attribute problem #48627 (thanks to Eric Celeste, IMALPASS) 0.04 Wed Apr 15 09:22:59 2009 - Updated POD (thanks to Mr. Grue) 0.03 Sun Apr 05 13:22:21 2009 - param method for Net::Google::Spreadsheets::Row (thanks to Mr. Grue) 0.02 Sat Apr 04 22:32:40 2009 - Crypt::SSLeay dependency - Better error message on login failure (thanks to Mr. Grue) 0.01 Tue Dec 16 23:52:25 2008 - original version diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index 11763d0..114af3a 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,311 +1,348 @@ package Net::Google::Spreadsheets; use Any::Moose; use Net::Google::DataAPI; use namespace::autoclean; use 5.008001; use Net::Google::AuthSub; use Net::Google::DataAPI::Auth::AuthSub; our $VERSION = '0.07'; with 'Net::Google::DataAPI::Role::Service'; has '+gdata_version' => (default => '3.0'); has '+namespaces' => ( default => sub { { gs => 'http://schemas.google.com/spreadsheets/2006', gsx => 'http://schemas.google.com/spreadsheets/2006/extended', batch => 'http://schemas.google.com/gdata/batch', } }, ); has username => (is => 'ro', isa => 'Str'); has password => (is => 'ro', isa => 'Str'); has account_type => (is => 'ro', isa => 'Str', required => 1, default => 'HOSTED_OR_GOOGLE'); has source => (is => 'ro', isa => 'Str', required => 1, default => __PACKAGE__ . '-' . $VERSION); sub _build_auth { my ($self) = @_; my $authsub = Net::Google::AuthSub->new( source => $self->source, service => 'wise', account_type => $self->account_type, ); my $res = $authsub->login( $self->username, $self->password ); unless ($res && $res->is_success) { die 'Net::Google::AuthSub login failed'; } return Net::Google::DataAPI::Auth::AuthSub->new( authsub => $authsub, ); } feedurl spreadsheet => ( default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full', entry_class => 'Net::Google::Spreadsheets::Spreadsheet', can_add => 0, ); around spreadsheets => sub { my ($next, $self, $args) = @_; my @result = $next->($self, $args); if (my $key = $args->{key}) { @result = grep {$_->key eq $key} @result; } return @result; }; sub BUILD { my $self = shift; $self->auth; } __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, {row => 1, col => 4, input_value => 'age'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # fetch rows my @rows = $worksheet->rows; # or fetch rows with query @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); # delete the row $row->delete; # delete the worksheet $worksheet->delete; # create a table my $table = $spreadsheet->add_table( { worksheet => $new_worksheet, columns => ['name', 'nick', 'mail address', 'age'], } ); # add a record my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', 'mail address' => '[email protected]', age => '33', } ); # find a record my $found = $table->record( { sq => '"mail address" = "[email protected]"' } ); # delete it $found->delete; # delete table $table->delete; =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 4 =item username Username for Google. This should be full email address format like '[email protected]'. =item password Password corresponding to the username. =item source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 4 =item title title of the spreadsheet. =item title-exact whether title search should match exactly or not. =item key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. +=head1 AUTHORIZATIONS + +you can optionally pass auth object argument when initializing +Net::Google::Spreadsheets instance. + +If you want to use AuthSub mechanism, make Net::Google::DataAPI::Auth::AuthSub +object and path it to the constructor: + + my $authsub = Net::Google::AuthSub->new; + $authsub->auth(undef, $session_token); + my $auth = Net::Google::DataAPI::Auth::AuthSub->new( + authsub => $authsub + ); + + my $service = Net::Google::Spreadsheet->new( + auth => $auth + ); + +In OAuth case, like this: + + my $oauth = Net::Google::DataAPI::Auth::OAuth->new( + consumer_key => 'consumer.example.com', + consumer_secret => 'mys3cr3t', + callback => 'http://consumer.example.com/callback', + ); + $oauth->get_request_token; + my $url = $oauth->get_authorize_token_url; + # show the url to the user and get the $verifier value + $oauth->get_access_token({verifier => $verifier}); + my $service = Net::Google::Spreadsheet->new( + auth => $oauth + ); + =head1 TESTING To test this module, you have to prepare as below. =over 4 =item create a spreadsheet by hand Go to L<http://docs.google.com> and create a spreadsheet. =item set SPREADSHEET_TITLE environment variable export SPREADSHEET_TITLE='my test spreadsheet' or so. =item set username and password for google.com via Config::Pit install Config::Pit and type ppit set google.com then some editor comes up and type your username and password like --- username: [email protected] password: foobarbaz =item run tests as always, perl Makefile.PL make make test =back =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> +L<Net::Google::DataAPI> + +L<Net::OAuth> + L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Record> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/xt/01_podspell.t b/xt/01_podspell.t index 5f27824..002febe 100644 --- a/xt/01_podspell.t +++ b/xt/01_podspell.t @@ -1,21 +1,24 @@ use Test::More; eval q{ use Test::Spelling }; plan skip_all => "Test::Spelling is not installed." if $@; add_stopwords(map { split /[\s\:\-]/ } <DATA>); $ENV{LANG} = 'C'; all_pod_files_spelling_ok('lib'); __DATA__ Nobuo Danjou [email protected] Net::Google::Spreadsheets API username google orderby UserAgent col min sq rewritable param com +oauth +AuthSub +auth
lopnor/Net-Google-Spreadsheets
35318d59d1a9b97a6a706ca5b13123dc81998dbc
depends on Net::Google::DataAPI 0.09
diff --git a/MANIFEST b/MANIFEST index ec3adf2..4a0b2d1 100644 --- a/MANIFEST +++ b/MANIFEST @@ -1,48 +1,49 @@ Changes inc/Module/Install.pm +inc/Module/Install/Any/Moose.pm inc/Module/Install/AuthorTests.pm inc/Module/Install/Base.pm inc/Module/Install/Can.pm inc/Module/Install/Fetch.pm inc/Module/Install/Include.pm inc/Module/Install/Makefile.pm inc/Module/Install/Metadata.pm inc/Module/Install/Repository.pm inc/Module/Install/TestBase.pm inc/Module/Install/Win32.pm inc/Module/Install/WriteAll.pm inc/Spiffy.pm inc/Test/Base.pm inc/Test/Base/Filter.pm inc/Test/Builder.pm inc/Test/Builder/Module.pm inc/Test/Exception.pm inc/Test/MockModule.pm inc/Test/MockObject.pm inc/Test/More.pm lib/Net/Google/Spreadsheets.pm lib/Net/Google/Spreadsheets/Cell.pm lib/Net/Google/Spreadsheets/Record.pm lib/Net/Google/Spreadsheets/Row.pm lib/Net/Google/Spreadsheets/Spreadsheet.pm lib/Net/Google/Spreadsheets/Table.pm lib/Net/Google/Spreadsheets/Worksheet.pm Makefile.PL MANIFEST This list of files META.yml README t/00_compile.t t/01_instanciate.t t/02_spreadsheet.t t/03_worksheet.t t/04_cell.t t/05_row.t t/06_table.t t/07_record.t t/08_error.t t/Util.pm xt/01_podspell.t xt/02_perlcritic.t xt/03_pod.t xt/04_synopsis.t xt/perlcriticrc diff --git a/Makefile.PL b/Makefile.PL index 058da94..824d043 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,22 +1,27 @@ use inc::Module::Install; name 'Net-Google-Spreadsheets'; all_from 'lib/Net/Google/Spreadsheets.pm'; requires 'Carp'; requires 'XML::Atom'; -requires 'Moose' => '0.34'; -requires 'Net::Google::DataAPI' => '0.04'; +requires 'Net::Google::AuthSub'; +requires 'Net::Google::DataAPI' => '0.09'; requires 'URI'; requires 'Path::Class'; +requires 'namespace::autoclean'; +requires_any_moose( + moose => '0.56', + mouse => '0.40', +); tests_recursive; author_tests 'xt'; build_requires 'Test::More' => '0.88'; build_requires 'Test::Exception'; build_requires 'Test::MockModule'; build_requires 'Test::MockObject'; use_test_base; auto_include; auto_set_repository; WriteAll; diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index f74bf46..11763d0 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,282 +1,311 @@ package Net::Google::Spreadsheets; -use Moose; +use Any::Moose; use Net::Google::DataAPI; -use namespace::clean -except => 'meta'; +use namespace::autoclean; use 5.008001; +use Net::Google::AuthSub; +use Net::Google::DataAPI::Auth::AuthSub; our $VERSION = '0.07'; -with 'Net::Google::DataAPI::Role::Service' => { - gdata_version => '3.0', - service => 'wise', - source => __PACKAGE__.'-'.$VERSION, - ns => { - gs => 'http://schemas.google.com/spreadsheets/2006', - gsx => 'http://schemas.google.com/spreadsheets/2006/extended', - batch => 'http://schemas.google.com/gdata/batch', +with 'Net::Google::DataAPI::Role::Service'; +has '+gdata_version' => (default => '3.0'); +has '+namespaces' => ( + default => sub { + { + gs => 'http://schemas.google.com/spreadsheets/2006', + gsx => 'http://schemas.google.com/spreadsheets/2006/extended', + batch => 'http://schemas.google.com/gdata/batch', + } + }, +); + +has username => (is => 'ro', isa => 'Str'); +has password => (is => 'ro', isa => 'Str'); +has account_type => (is => 'ro', isa => 'Str', required => 1, default => 'HOSTED_OR_GOOGLE'); +has source => (is => 'ro', isa => 'Str', required => 1, default => __PACKAGE__ . '-' . $VERSION); + +sub _build_auth { + my ($self) = @_; + my $authsub = Net::Google::AuthSub->new( + source => $self->source, + service => 'wise', + account_type => $self->account_type, + ); + my $res = $authsub->login( $self->username, $self->password ); + unless ($res && $res->is_success) { + die 'Net::Google::AuthSub login failed'; } -}; + return Net::Google::DataAPI::Auth::AuthSub->new( + authsub => $authsub, + ); +} feedurl spreadsheet => ( default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full', entry_class => 'Net::Google::Spreadsheets::Spreadsheet', can_add => 0, ); around spreadsheets => sub { my ($next, $self, $args) = @_; my @result = $next->($self, $args); if (my $key = $args->{key}) { @result = grep {$_->key eq $key} @result; } return @result; }; +sub BUILD { + my $self = shift; + $self->auth; +} + __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, {row => 1, col => 4, input_value => 'age'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # fetch rows my @rows = $worksheet->rows; # or fetch rows with query @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); # delete the row $row->delete; # delete the worksheet $worksheet->delete; # create a table my $table = $spreadsheet->add_table( { worksheet => $new_worksheet, columns => ['name', 'nick', 'mail address', 'age'], } ); # add a record my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', 'mail address' => '[email protected]', age => '33', } ); # find a record my $found = $table->record( { sq => '"mail address" = "[email protected]"' } ); # delete it $found->delete; # delete table $table->delete; =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 4 =item username Username for Google. This should be full email address format like '[email protected]'. =item password Password corresponding to the username. =item source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 4 =item title title of the spreadsheet. =item title-exact whether title search should match exactly or not. =item key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 TESTING To test this module, you have to prepare as below. =over 4 =item create a spreadsheet by hand Go to L<http://docs.google.com> and create a spreadsheet. =item set SPREADSHEET_TITLE environment variable export SPREADSHEET_TITLE='my test spreadsheet' or so. =item set username and password for google.com via Config::Pit install Config::Pit and type ppit set google.com then some editor comes up and type your username and password like --- username: [email protected] password: foobarbaz =item run tests as always, perl Makefile.PL make make test =back =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Record> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Net/Google/Spreadsheets/Cell.pm b/lib/Net/Google/Spreadsheets/Cell.pm index d2046a6..52f111c 100644 --- a/lib/Net/Google/Spreadsheets/Cell.pm +++ b/lib/Net/Google/Spreadsheets/Cell.pm @@ -1,122 +1,122 @@ package Net::Google::Spreadsheets::Cell; -use Moose; -use namespace::clean -except => 'meta'; +use Any::Moose; +use namespace::autoclean; use XML::Atom::Util qw(first); with 'Net::Google::DataAPI::Role::Entry'; has content => ( isa => 'Str', is => 'ro', ); has row => ( isa => 'Int', is => 'ro', ); has col => ( isa => 'Int', is => 'ro', ); has input_value => ( isa => 'Str', is => 'rw', trigger => sub {$_[0]->update}, ); after from_atom => sub { my ($self) = @_; my $elem = first( $self->elem, $self->ns('gs')->{uri}, 'cell'); $self->{row} = $elem->getAttribute('row'); $self->{col} = $elem->getAttribute('col'); $self->{input_value} = $elem->getAttribute('inputValue'); $self->{content} = $elem->textContent || ''; }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->ns('gs'), 'cell', '', { row => $self->row, col => $self->col, inputValue => $self->input_value, } ); my $link = XML::Atom::Link->new; $link->rel('edit'); $link->type('application/atom+xml'); $link->href($self->editurl); $entry->link($link); $entry->id($self->id); return $entry; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Cell - A representation class for Google Spreadsheet cell. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a cell my $cell = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->cell( { col => 1, row => 1, } ); # update a cell $cell->input_value('new value'); # get the content of a cell my $value = $cell->content; =head1 ATTRIBUTES =head2 input_value Rewritable attribute. You can set formula like '=A1+B1' or so. =head2 content Read only attribute. You can get the result of formula. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Record.pm b/lib/Net/Google/Spreadsheets/Record.pm index 2f932ab..c1e4191 100644 --- a/lib/Net/Google/Spreadsheets/Record.pm +++ b/lib/Net/Google/Spreadsheets/Record.pm @@ -1,117 +1,117 @@ package Net::Google::Spreadsheets::Record; -use Moose; -use namespace::clean -except => 'meta'; +use Any::Moose; +use namespace::autoclean; use XML::Atom::Util qw(nodelist); with 'Net::Google::DataAPI::Role::Entry', 'Net::Google::DataAPI::Role::HasContent'; after from_atom => sub { my ($self) = @_; for my $node (nodelist($self->elem, $self->ns('gs')->{uri}, 'field')) { $self->{content}->{$node->getAttribute('name')} = $node->textContent; } }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->{content}}) { $entry->add($self->ns('gs'), 'field', $value, {name => $key}); } return $entry; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Record - A representation class for Google Spreadsheet record. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a record my $record = $service->spreadsheet( { title => 'list for new year cards', } )->table( { title => 'addressbook', } )->record( { sq => 'id = 1000', } ); # get the content of a row my $hashref = $record->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $record->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $record->param('name'); # returns 'Nobuo Danjou' my $newval = $record->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new record value (with all fields) my $hashref2 = $record->param; # same as $record->content; =head1 METHODS =head2 param sets and gets content value. =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Row> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Row.pm b/lib/Net/Google/Spreadsheets/Row.pm index ebbdc96..de14ab4 100644 --- a/lib/Net/Google/Spreadsheets/Row.pm +++ b/lib/Net/Google/Spreadsheets/Row.pm @@ -1,155 +1,155 @@ package Net::Google::Spreadsheets::Row; -use Moose; -use namespace::clean -except => 'meta'; +use Any::Moose; +use namespace::autoclean; use Net::Google::DataAPI; use XML::Atom::Util qw(nodelist); with 'Net::Google::DataAPI::Role::Entry', 'Net::Google::DataAPI::Role::HasContent'; after from_atom => sub { my ($self) = @_; for my $node (nodelist($self->elem, $self->ns('gsx')->{uri}, '*')) { $self->{content}->{$node->localname} = $node->textContent; } }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->{content}}) { $entry->set($self->ns('gsx'), $key, $value); } return $entry; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Row - A representation class for Google Spreadsheet row. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a row my $row = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->row( { sq => 'id = 1000' } ); # get the content of a row my $hashref = $row->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $row->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $row->param('name'); # returns 'Nobuo Danjou' my $newval = $row->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new row value (with all fields) my $hashref2 = $row->param; # same as $row->content; =head1 METHODS =head2 param sets and gets content value. =head1 CAVEATS Space characters in hash key of rows will be removed when you access rows. See below. my $ws = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'})->worksheet(1); $ws->batchupdate_cell( {col => 1,row => 1, input_value => 'name'}, {col => 2,row => 1, input_value => 'mail address'}, ); $ws->add_row( { name => 'my name', mailaddress => '[email protected]', # above passes, below fails. # 'mail address' => '[email protected]', } ); Instead, Net::Google::Spreadsheets::Table and Net::Google::Spreadsheets::Record allows space characters in column name. my $s = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'}); my $t = $s->add_table( { worksheet => $s->worksheet(1), columns => ['name', 'mail address'], } ); $t->add_record( { name => 'my name', 'mail address' => '[email protected]', } ); =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Spreadsheet.pm b/lib/Net/Google/Spreadsheets/Spreadsheet.pm index 7e6821a..9b1db57 100644 --- a/lib/Net/Google/Spreadsheets/Spreadsheet.pm +++ b/lib/Net/Google/Spreadsheets/Spreadsheet.pm @@ -1,230 +1,230 @@ package Net::Google::Spreadsheets::Spreadsheet; -use Moose; -use namespace::clean -except => 'meta'; +use Any::Moose; +use namespace::autoclean; use Net::Google::DataAPI; with 'Net::Google::DataAPI::Role::Entry'; use Path::Class; use URI; has title => ( is => 'ro', ); entry_has key => ( isa => 'Str', is => 'ro', from_atom => sub { my ($self, $atom) = @_; return file(URI->new($self->id)->path)->basename; }, ); feedurl worksheet => ( entry_class => 'Net::Google::Spreadsheets::Worksheet', as_content_src => 1, ); feedurl table => ( entry_class => 'Net::Google::Spreadsheets::Table', rel => 'http://schemas.google.com/spreadsheets/2006#tablesfeed', ); __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Spreadsheet - Representation of spreadsheet. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # create a worksheet my $worksheet = $spreadsheet->add_worksheet( { title => 'foobar', col_count => 10, row_count => 100, } ); # list worksheets my @ws = $spreadsheet->worksheets; # find a worksheet my $ws = $spreadsheet->worksheet({title => 'fooba'}); # create a table my $table = $spreadsheet->add_table( { title => 'sample table', worksheet => $worksheet, columns => ['id', 'username', 'mail', 'password'], } ); # list tables my @t = $spreadsheet->tables; # find a worksheet my $t = $spreadsheet->table({title => 'sample table'}); =head1 METHODS =head2 worksheets(\%condition) Returns a list of Net::Google::Spreadsheets::Worksheet objects. Acceptable arguments are: =over 4 =item title =item title-exact =back =head2 worksheet(\%condition) Returns first item of worksheets(\%condition) if available. =head2 add_worksheet(\%attribuets) Creates new worksheet and returns a Net::Google::Spreadsheets::Worksheet object representing it. Arguments (all optional) are: =over 4 =item title =item col_count =item row_count =back =head2 tables(\%condition) Returns a list of Net::Google::Spreadsheets::Table objects. Acceptable arguments are: =over 4 =item title =item title-exact =back =head2 table(\%condition) Returns first item of tables(\%condition) if available. =head2 add_table(\%attribuets) Creates new table and returns a Net::Google::Spreadsheets::Table object representing it. Arguments are: =over 4 =item title (optional) =item summary (optional) =item worksheet Worksheet where the table lives. worksheet instance or the title. =item header (optional, default = 1) Row number of header =item start_row (optional, default = 2) The index of the first row of the data section. =item insertion_mode (optional, default = 'overwrite') Insertion mode. 'insert' inserts new row into the worksheet when creating record, 'overwrite' tries to use existing rows in the worksheet. =item columns Columns of the table. you can specify them as hashref, arrayref, arrayref of hashref. $ss->add_table( { worksheet => $ws, columns => [ {index => 1, name => 'foo'}, {index => 2, name => 'bar'}, {index => 3, name => 'baz'}, ], } ); $ss->add_table( { worksheet => $ws, columns => { A => 'foo', B => 'bar', C => 'baz', } } ); $ss->add_table( { worksheet => $ws, columns => ['foo', 'bar', 'baz'], } ); 'index' of the first case and hash key of the second case is column index of the worksheet. In the third case, the columns is automatically placed to the columns of the worksheet from 'A' to 'Z' order. =back =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Table> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Table.pm b/lib/Net/Google/Spreadsheets/Table.pm index bed38df..0f331a0 100644 --- a/lib/Net/Google/Spreadsheets/Table.pm +++ b/lib/Net/Google/Spreadsheets/Table.pm @@ -1,228 +1,228 @@ package Net::Google::Spreadsheets::Table; -use Moose; -use Moose::Util::TypeConstraints; -use namespace::clean -except => 'meta'; +use Any::Moose; +use Any::Moose '::Util::TypeConstraints'; +use namespace::autoclean; use Net::Google::DataAPI; use XML::Atom::Util qw(nodelist first create_element); with 'Net::Google::DataAPI::Role::Entry'; subtype 'ColumnList' => as 'ArrayRef[Net::Google::Spreadsheets::Table::Column]'; coerce 'ColumnList' => from 'ArrayRef[HashRef]' => via { [ map {Net::Google::Spreadsheets::Table::Column->new($_)} @$_ ] }; coerce 'ColumnList' => from 'ArrayRef[Str]' => via { my @c; my $index = 0; for my $value (@$_) { push @c, Net::Google::Spreadsheets::Table::Column->new( index => ++$index, name => $value, ); } \@c; }; coerce 'ColumnList' => from 'HashRef' => via { my @c; while (my ($key, $value) = each(%$_)) { push @c, Net::Google::Spreadsheets::Table::Column->new( index => $key, name => $value, ); } \@c; }; subtype 'WorksheetName' => as 'Str'; coerce 'WorksheetName' => from 'Net::Google::Spreadsheets::Worksheet' => via { $_->title }; feedurl record => ( entry_class => 'Net::Google::Spreadsheets::Record', arg_builder => sub { my ($self, $args) = @_; return {content => $args}; }, as_content_src => 1, ); has summary => ( is => 'rw', isa => 'Str' ); has worksheet => ( is => 'ro', isa => 'WorksheetName', coerce => 1 ); has header => ( is => 'ro', isa => 'Int', required => 1, default => 1 ); has start_row => ( is => 'ro', isa => 'Int', required => 1, default => 2 ); has num_rows => ( is => 'ro', isa => 'Int' ); has columns => ( is => 'ro', isa => 'ColumnList', coerce => 1 ); has insertion_mode => ( is => 'ro', isa => (enum ['insert', 'overwrite']), default => 'overwrite' ); after from_atom => sub { my ($self) = @_; my $gsns = $self->ns('gs')->{uri}; my $elem = $self->elem; $self->{summary} = $self->atom->summary; $self->{worksheet} = first( $elem, $gsns, 'worksheet')->getAttribute('name'); $self->{header} = first( $elem, $gsns, 'header')->getAttribute('row'); my @columns; my $data = first($elem, $gsns, 'data'); $self->{insertion_mode} = $data->getAttribute('insertionMode'); $self->{start_row} = $data->getAttribute('startRow'); $self->{num_rows} = $data->getAttribute('numRows'); for (nodelist($data, $gsns, 'column')) { push @columns, Net::Google::Spreadsheets::Table::Column->new( index => $_->getAttribute('index'), name => $_->getAttribute('name'), ); } $self->{columns} = \@columns; }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); my $gsns = $self->ns('gs')->{uri}; $entry->summary($self->summary) if $self->summary; $entry->set($gsns, 'worksheet', '', {name => $self->worksheet}); $entry->set($gsns, 'header', '', {row => $self->header}); my $data = create_element($gsns, 'data'); $data->setAttribute(startRow => $self->start_row); $data->setAttribute(insertionMode => $self->insertion_mode); $data->setAttribute(startRow => $self->start_row) if $self->start_row; for ( @{$self->columns} ) { my $column = create_element($gsns, 'column'); $column->setAttribute(index => $_->index); $column->setAttribute(name => $_->name); $data->appendChild($column); } $entry->set($gsns, 'data', $data); return $entry; }; __PACKAGE__->meta->make_immutable; package # hide from PAUSE Net::Google::Spreadsheets::Table::Column; -use Moose; +use Any::Moose; has 'index' => ( is => 'ro', isa => 'Str' ); has 'name' => ( is => 'ro', isa => 'Str' ); __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Table - A representation class for Google Spreadsheet table. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a table my $table = $service->spreadsheet( { title => 'list for new year cards', } )->table( { title => 'sample table', } ); # create a record my $r = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # get records my @records = $table->records; # search records @records = $table->records({sq => 'age > 20'}); # search a record my $record = $table->record({sq => 'name = "Nobuo Danjou"'}); =head1 METHODS =head2 records(\%condition) Returns a list of Net::Google::Spreadsheets::Record objects. Acceptable arguments are: =over 4 =item sq Structured query on the full text in the worksheet. see the URL below for detail. =item orderby Set column name to use for ordering. =item reverse Set 'true' or 'false'. The default is 'false'. =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#RecordParameters> for details. =head2 record(\%condition) Returns first item of records(\%condition) if available. =head2 add_record(\%contents) Creates new record and returns a Net::Google::Spreadsheets::Record object representing it. Arguments are contents of a row as a hashref. my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Record> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Worksheet.pm b/lib/Net/Google/Spreadsheets/Worksheet.pm index 817d762..262ac58 100644 --- a/lib/Net/Google/Spreadsheets/Worksheet.pm +++ b/lib/Net/Google/Spreadsheets/Worksheet.pm @@ -1,247 +1,247 @@ package Net::Google::Spreadsheets::Worksheet; -use Moose; -use namespace::clean -except => 'meta'; +use Any::Moose; +use namespace::autoclean; use Net::Google::DataAPI; with 'Net::Google::DataAPI::Role::Entry'; use Carp; use Net::Google::Spreadsheets::Cell; use XML::Atom::Util qw(first); feedurl row => ( entry_class => 'Net::Google::Spreadsheets::Row', as_content_src => 1, arg_builder => sub { my ($self, $args) = @_; return {content => $args}; }, ); feedurl cell => ( entry_class => 'Net::Google::Spreadsheets::Cell', can_add => 0, rel => 'http://schemas.google.com/spreadsheets/2006#cellsfeed', query_builder => sub { my ($self, $args) = @_; if (my $col = delete $args->{col}) { $args->{'max-col'} = $col; $args->{'min-col'} = $col; $args->{'return-empty'} = 'true'; } if (my $row = delete $args->{row}) { $args->{'max-row'} = $row; $args->{'min-row'} = $row; $args->{'return-empty'} = 'true'; } return $args; }, ); entry_has row_count => ( isa => 'Int', is => 'rw', default => 100, tagname => 'rowCount', ns => 'gs', ); entry_has col_count => ( isa => 'Int', is => 'rw', default => 20, tagname => 'colCount', ns => 'gs', ); __PACKAGE__->meta->make_immutable; sub batchupdate_cell { my ($self, @args) = @_; my $feed = XML::Atom::Feed->new; for ( @args ) { my $id = sprintf("%s/R%sC%s",$self->cell_feedurl, $_->{row}, $_->{col}); $_->{id} = $_->{editurl} = $id; $_->{container} = $self, my $entry = Net::Google::Spreadsheets::Cell->new($_)->to_atom; $entry->set($self->ns('batch'), operation => '', {type => 'update'}); $entry->set($self->ns('batch'), id => $id); $feed->add_entry($entry); } my $res_feed = $self->service->post( $self->cell_feedurl."/batch", $feed, {'If-Match' => '*'} ); $self->sync; return map { Net::Google::Spreadsheets::Cell->new( atom => $_, container => $self, ) } grep { my $node = first( $_->elem, $self->ns('batch')->{uri}, 'status' ); $node->getAttribute('code') == 200; } $res_feed->entries; } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Worksheet - Representation of worksheet. =head1 SYNOPSIS my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); my $ss = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); my $worksheet = $ss->worksheet({title => 'Sheet1'}); # update cell by batch request $worksheet->batchupdate_cell( {col => 1, row => 1, input_value => 'name'}, {col => 2, row => 1, input_value => 'nick'}, {col => 3, row => 1, input_value => 'mail'}, {col => 4, row => 1, input_value => 'age'}, ); # get a cell object my $cell = $worksheet->cell({col => 1, row => 1}); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # get rows my @rows = $worksheet->rows; # search rows @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); =head1 METHODS =head2 rows(\%condition) Returns a list of Net::Google::Spreadsheets::Row objects. Acceptable arguments are: =over 4 =item sq Structured query on the full text in the worksheet. see the URL below for detail. =item orderby Set column name to use for ordering. =item reverse Set 'true' or 'false'. The default is 'false'. =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#ListParameters> for details. =head2 row(\%condition) Returns first item of rows(\%condition) if available. =head2 add_row(\%contents) Creates new row and returns a Net::Google::Spreadsheets::Row object representing it. Arguments are contents of a row as a hashref. my $row = $ws->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); =head2 cells(\%args) Returns a list of Net::Google::Spreadsheets::Cell objects. Acceptable arguments are: =over 4 =item min-row =item max-row =item min-col =item max-col =item range =item return-empty =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#CellParameters> for details. =head2 cell(\%args) Returns Net::Google::Spreadsheets::Cell object. Arguments are: =over 4 =item col =item row =back =head2 batchupdate_cell(@args) update multiple cells with a batch request. Pass a list of hash references containing: =over 4 =item col =item row =item input_value =back =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/t/08_error.t b/t/08_error.t index 6459e7c..a3e7c3f 100644 --- a/t/08_error.t +++ b/t/08_error.t @@ -1,78 +1,80 @@ use strict; use Test::More; use Test::Exception; use Test::MockModule; use Test::MockObject; use LWP::UserAgent; use Net::Google::Spreadsheets; throws_ok { my $service = Net::Google::Spreadsheets->new( username => 'foo', password => 'bar', ); } qr{Net::Google::AuthSub login failed}; { my $res = Test::MockObject->new; $res->mock(is_success => sub {return 1}); - $res->mock(auth => sub {return 'foobar'}); my $auth = Test::MockModule->new('Net::Google::AuthSub'); $auth->mock('login' => sub {return $res}); + $auth->mock(auth_params => sub {return (Authorization => 'GoogleLogin auth="foobar"')}); ok my $service = Net::Google::Spreadsheets->new( username => 'foo', password => 'bar', ); - is $service->ua->default_headers->header('Authorization'), 'GoogleLogin auth=foobar'; my $ua = Test::MockModule->new('LWP::UserAgent'); { - $ua->mock('request' => sub {return HTTP::Response->parse(<<'END')}); -302 Found -Location: http://www.google.com/ - -END + $ua->mock('request' => sub { + my ($self, $req) = @_; + is $req->header('Authorization'), 'GoogleLogin auth="foobar"'; + my $res = HTTP::Response->new(302); + $res->header(Location => 'http://www.google.com/'); + return $res; + } + ); throws_ok { $service->spreadsheets; } qr{302 Found}; } { $ua->mock('request' => sub {return HTTP::Response->parse(<<END)}); 200 OK Content-Type: application/atom+xml Content-Length: 1 1 END throws_ok { $service->spreadsheets; } qr{broken}; } { $ua->mock('request' => sub {return HTTP::Response->parse(<<END)}); 200 OK Content-Type: text/html Content-Length: 13 <html></html> END throws_ok { $service->spreadsheets; } qr{is not 'application/atom\+xml'}; } { $ua->mock('request' => sub {return HTTP::Response->parse(<<'END')}); 200 OK ETag: W/"hogehoge" Content-Type: application/atom+xml; charset=UTF-8; type=feed Content-Length: 958 <?xml version='1.0' encoding='UTF-8'?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearch/1.1/' xmlns:gd='http://schemas.google.com/g/2005' gd:etag='W/&quot;hogehoge&quot;'><id>http://spreadsheets.google.com/feeds/spreadsheets/private/full</id><updated>2009-08-15T09:41:23.289Z</updated><category scheme='http://schemas.google.com/spreadsheets/2006' term='http://schemas.google.com/spreadsheets/2006#spreadsheet'/><title>Available Spreadsheets - [email protected]</title><link rel='alternate' type='text/html' href='http://docs.google.com'/><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://spreadsheets.google.com/feeds/spreadsheets/private/full'/><link rel='self' type='application/atom+xml' href='http://spreadsheets.google.com/feeds/spreadsheets/private/full?tfe='/><openSearch:totalResults>0</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex></feed> END my @ss = $service->spreadsheets; is scalar @ss, 0; } } done_testing; diff --git a/xt/perlcriticrc b/xt/perlcriticrc index fa96144..0910b96 100644 --- a/xt/perlcriticrc +++ b/xt/perlcriticrc @@ -1,2 +1,5 @@ [TestingAndDebugging::ProhibitNoStrict] allow=refs + +[TestingAndDebugging::RequireUseStrict] +equivalent_modules = Any::Moose
lopnor/Net-Google-Spreadsheets
a562723584e49cf4a5094de615d31d98819fba0a
query spreadsheets with key
diff --git a/Makefile.PL b/Makefile.PL index b54d9ea..058da94 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,22 +1,22 @@ use inc::Module::Install; name 'Net-Google-Spreadsheets'; all_from 'lib/Net/Google/Spreadsheets.pm'; requires 'Carp'; requires 'XML::Atom'; -requires 'Moose' => 0.34; -requires 'Net::Google::DataAPI'; +requires 'Moose' => '0.34'; +requires 'Net::Google::DataAPI' => '0.04'; requires 'URI'; requires 'Path::Class'; tests_recursive; author_tests 'xt'; build_requires 'Test::More' => '0.88'; build_requires 'Test::Exception'; build_requires 'Test::MockModule'; build_requires 'Test::MockObject'; use_test_base; auto_include; auto_set_repository; WriteAll; diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index 3b6be64..f74bf46 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,272 +1,282 @@ package Net::Google::Spreadsheets; use Moose; use Net::Google::DataAPI; use namespace::clean -except => 'meta'; use 5.008001; our $VERSION = '0.07'; with 'Net::Google::DataAPI::Role::Service' => { + gdata_version => '3.0', service => 'wise', source => __PACKAGE__.'-'.$VERSION, ns => { gs => 'http://schemas.google.com/spreadsheets/2006', gsx => 'http://schemas.google.com/spreadsheets/2006/extended', batch => 'http://schemas.google.com/gdata/batch', } }; feedurl spreadsheet => ( default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full', entry_class => 'Net::Google::Spreadsheets::Spreadsheet', can_add => 0, ); +around spreadsheets => sub { + my ($next, $self, $args) = @_; + my @result = $next->($self, $args); + if (my $key = $args->{key}) { + @result = grep {$_->key eq $key} @result; + } + return @result; +}; + __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, {row => 1, col => 4, input_value => 'age'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # fetch rows my @rows = $worksheet->rows; # or fetch rows with query @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); # delete the row $row->delete; # delete the worksheet $worksheet->delete; # create a table my $table = $spreadsheet->add_table( { worksheet => $new_worksheet, columns => ['name', 'nick', 'mail address', 'age'], } ); # add a record my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', 'mail address' => '[email protected]', age => '33', } ); # find a record my $found = $table->record( { sq => '"mail address" = "[email protected]"' } ); # delete it $found->delete; # delete table $table->delete; =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 4 =item username Username for Google. This should be full email address format like '[email protected]'. =item password Password corresponding to the username. =item source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 4 =item title title of the spreadsheet. =item title-exact whether title search should match exactly or not. =item key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 TESTING To test this module, you have to prepare as below. =over 4 =item create a spreadsheet by hand Go to L<http://docs.google.com> and create a spreadsheet. =item set SPREADSHEET_TITLE environment variable export SPREADSHEET_TITLE='my test spreadsheet' or so. =item set username and password for google.com via Config::Pit install Config::Pit and type ppit set google.com then some editor comes up and type your username and password like --- username: [email protected] password: foobarbaz =item run tests as always, perl Makefile.PL make make test =back =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Record> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
lopnor/Net-Google-Spreadsheets
359b23dde0aa293dbcd415742ee41f1b39bf87fc
prepare for 0.07
diff --git a/Changes b/Changes index 24c2bda..6f67c25 100644 --- a/Changes +++ b/Changes @@ -1,26 +1,29 @@ Revision history for Perl extension Net::Google::Spreadsheets +0.07 Tue Sep 22 18:11:09 2009 + - Use Net::Google::DataAPI + 0.06 Thu Aug 20 23:21:35 2009 - Refactored internals 0.06_01 Mon Arg 16 16:01:27 2009 - Supports Google Spreadsheets API version 3.0 - Add table and record feeds supports - Better error handlings (no more redirects, captures xml parse error, and more) - Refactored internals 0.05 Sun Aug 15 09:47:50 2009 - Fix Moose attribute problem #48627 (thanks to Eric Celeste, IMALPASS) 0.04 Wed Apr 15 09:22:59 2009 - Updated POD (thanks to Mr. Grue) 0.03 Sun Apr 05 13:22:21 2009 - param method for Net::Google::Spreadsheets::Row (thanks to Mr. Grue) 0.02 Sat Apr 04 22:32:40 2009 - Crypt::SSLeay dependency - Better error message on login failure (thanks to Mr. Grue) 0.01 Tue Dec 16 23:52:25 2008 - original version diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index b35edd7..3b6be64 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,272 +1,272 @@ package Net::Google::Spreadsheets; use Moose; use Net::Google::DataAPI; use namespace::clean -except => 'meta'; use 5.008001; -our $VERSION = '0.06'; +our $VERSION = '0.07'; with 'Net::Google::DataAPI::Role::Service' => { service => 'wise', source => __PACKAGE__.'-'.$VERSION, ns => { gs => 'http://schemas.google.com/spreadsheets/2006', gsx => 'http://schemas.google.com/spreadsheets/2006/extended', batch => 'http://schemas.google.com/gdata/batch', } }; feedurl spreadsheet => ( default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full', entry_class => 'Net::Google::Spreadsheets::Spreadsheet', can_add => 0, ); __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, {row => 1, col => 4, input_value => 'age'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # fetch rows my @rows = $worksheet->rows; # or fetch rows with query @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); # delete the row $row->delete; # delete the worksheet $worksheet->delete; # create a table my $table = $spreadsheet->add_table( { worksheet => $new_worksheet, columns => ['name', 'nick', 'mail address', 'age'], } ); # add a record my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', 'mail address' => '[email protected]', age => '33', } ); # find a record my $found = $table->record( { sq => '"mail address" = "[email protected]"' } ); # delete it $found->delete; # delete table $table->delete; =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 4 =item username Username for Google. This should be full email address format like '[email protected]'. =item password Password corresponding to the username. =item source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 4 =item title title of the spreadsheet. =item title-exact whether title search should match exactly or not. =item key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 TESTING To test this module, you have to prepare as below. =over 4 =item create a spreadsheet by hand Go to L<http://docs.google.com> and create a spreadsheet. =item set SPREADSHEET_TITLE environment variable export SPREADSHEET_TITLE='my test spreadsheet' or so. =item set username and password for google.com via Config::Pit install Config::Pit and type ppit set google.com then some editor comes up and type your username and password like --- username: [email protected] password: foobarbaz =item run tests as always, perl Makefile.PL make make test =back =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Record> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Net/Google/Spreadsheets/Spreadsheet.pm b/lib/Net/Google/Spreadsheets/Spreadsheet.pm index eb54614..7e6821a 100644 --- a/lib/Net/Google/Spreadsheets/Spreadsheet.pm +++ b/lib/Net/Google/Spreadsheets/Spreadsheet.pm @@ -1,231 +1,230 @@ package Net::Google::Spreadsheets::Spreadsheet; use Moose; use namespace::clean -except => 'meta'; use Net::Google::DataAPI; with 'Net::Google::DataAPI::Role::Entry'; use Path::Class; use URI; -has +title => ( +has title => ( is => 'ro', ); -has key => ( +entry_has key => ( isa => 'Str', is => 'ro', + from_atom => sub { + my ($self, $atom) = @_; + return file(URI->new($self->id)->path)->basename; + }, ); feedurl worksheet => ( entry_class => 'Net::Google::Spreadsheets::Worksheet', as_content_src => 1, ); feedurl table => ( entry_class => 'Net::Google::Spreadsheets::Table', rel => 'http://schemas.google.com/spreadsheets/2006#tablesfeed', ); -after from_atom => sub { - my ($self) = @_; - $self->{key} = file(URI->new($self->id)->path)->basename; -}; - __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Spreadsheet - Representation of spreadsheet. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # create a worksheet my $worksheet = $spreadsheet->add_worksheet( { title => 'foobar', col_count => 10, row_count => 100, } ); # list worksheets my @ws = $spreadsheet->worksheets; # find a worksheet my $ws = $spreadsheet->worksheet({title => 'fooba'}); # create a table my $table = $spreadsheet->add_table( { title => 'sample table', worksheet => $worksheet, columns => ['id', 'username', 'mail', 'password'], } ); # list tables my @t = $spreadsheet->tables; # find a worksheet my $t = $spreadsheet->table({title => 'sample table'}); =head1 METHODS =head2 worksheets(\%condition) Returns a list of Net::Google::Spreadsheets::Worksheet objects. Acceptable arguments are: =over 4 =item title =item title-exact =back =head2 worksheet(\%condition) Returns first item of worksheets(\%condition) if available. =head2 add_worksheet(\%attribuets) Creates new worksheet and returns a Net::Google::Spreadsheets::Worksheet object representing it. Arguments (all optional) are: =over 4 =item title =item col_count =item row_count =back =head2 tables(\%condition) Returns a list of Net::Google::Spreadsheets::Table objects. Acceptable arguments are: =over 4 =item title =item title-exact =back =head2 table(\%condition) Returns first item of tables(\%condition) if available. =head2 add_table(\%attribuets) Creates new table and returns a Net::Google::Spreadsheets::Table object representing it. Arguments are: =over 4 =item title (optional) =item summary (optional) =item worksheet Worksheet where the table lives. worksheet instance or the title. =item header (optional, default = 1) Row number of header =item start_row (optional, default = 2) The index of the first row of the data section. =item insertion_mode (optional, default = 'overwrite') Insertion mode. 'insert' inserts new row into the worksheet when creating record, 'overwrite' tries to use existing rows in the worksheet. =item columns Columns of the table. you can specify them as hashref, arrayref, arrayref of hashref. $ss->add_table( { worksheet => $ws, columns => [ {index => 1, name => 'foo'}, {index => 2, name => 'bar'}, {index => 3, name => 'baz'}, ], } ); $ss->add_table( { worksheet => $ws, columns => { A => 'foo', B => 'bar', C => 'baz', } } ); $ss->add_table( { worksheet => $ws, columns => ['foo', 'bar', 'baz'], } ); 'index' of the first case and hash key of the second case is column index of the worksheet. In the third case, the columns is automatically placed to the columns of the worksheet from 'A' to 'Z' order. =back =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Table> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Worksheet.pm b/lib/Net/Google/Spreadsheets/Worksheet.pm index 5ff1d31..817d762 100644 --- a/lib/Net/Google/Spreadsheets/Worksheet.pm +++ b/lib/Net/Google/Spreadsheets/Worksheet.pm @@ -1,259 +1,247 @@ package Net::Google::Spreadsheets::Worksheet; use Moose; use namespace::clean -except => 'meta'; use Net::Google::DataAPI; with 'Net::Google::DataAPI::Role::Entry'; use Carp; use Net::Google::Spreadsheets::Cell; use XML::Atom::Util qw(first); feedurl row => ( entry_class => 'Net::Google::Spreadsheets::Row', as_content_src => 1, arg_builder => sub { my ($self, $args) = @_; return {content => $args}; }, ); feedurl cell => ( entry_class => 'Net::Google::Spreadsheets::Cell', can_add => 0, rel => 'http://schemas.google.com/spreadsheets/2006#cellsfeed', query_builder => sub { my ($self, $args) = @_; if (my $col = delete $args->{col}) { $args->{'max-col'} = $col; $args->{'min-col'} = $col; $args->{'return-empty'} = 'true'; } if (my $row = delete $args->{row}) { $args->{'max-row'} = $row; $args->{'min-row'} = $row; $args->{'return-empty'} = 'true'; } return $args; }, ); -has row_count => ( +entry_has row_count => ( isa => 'Int', is => 'rw', default => 100, - trigger => sub {$_[0]->update} + tagname => 'rowCount', + ns => 'gs', ); -has col_count => ( +entry_has col_count => ( isa => 'Int', is => 'rw', default => 20, - trigger => sub {$_[0]->update} + tagname => 'colCount', + ns => 'gs', ); -around to_atom => sub { - my ($next, $self) = @_; - my $entry = $next->($self); - $entry->set($self->ns('gs'), 'rowCount', $self->row_count); - $entry->set($self->ns('gs'), 'colCount', $self->col_count); - return $entry; -}; - -after from_atom => sub { - my ($self) = @_; - $self->{row_count} = $self->atom->get($self->ns('gs'), 'rowCount'); - $self->{col_count} = $self->atom->get($self->ns('gs'), 'colCount'); -}; - __PACKAGE__->meta->make_immutable; sub batchupdate_cell { my ($self, @args) = @_; my $feed = XML::Atom::Feed->new; for ( @args ) { my $id = sprintf("%s/R%sC%s",$self->cell_feedurl, $_->{row}, $_->{col}); $_->{id} = $_->{editurl} = $id; $_->{container} = $self, my $entry = Net::Google::Spreadsheets::Cell->new($_)->to_atom; $entry->set($self->ns('batch'), operation => '', {type => 'update'}); $entry->set($self->ns('batch'), id => $id); $feed->add_entry($entry); } my $res_feed = $self->service->post( $self->cell_feedurl."/batch", $feed, {'If-Match' => '*'} ); $self->sync; return map { Net::Google::Spreadsheets::Cell->new( atom => $_, container => $self, ) } grep { my $node = first( $_->elem, $self->ns('batch')->{uri}, 'status' ); $node->getAttribute('code') == 200; } $res_feed->entries; } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Worksheet - Representation of worksheet. =head1 SYNOPSIS my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); my $ss = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); my $worksheet = $ss->worksheet({title => 'Sheet1'}); # update cell by batch request $worksheet->batchupdate_cell( {col => 1, row => 1, input_value => 'name'}, {col => 2, row => 1, input_value => 'nick'}, {col => 3, row => 1, input_value => 'mail'}, {col => 4, row => 1, input_value => 'age'}, ); # get a cell object my $cell = $worksheet->cell({col => 1, row => 1}); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # get rows my @rows = $worksheet->rows; # search rows @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); =head1 METHODS =head2 rows(\%condition) Returns a list of Net::Google::Spreadsheets::Row objects. Acceptable arguments are: =over 4 =item sq Structured query on the full text in the worksheet. see the URL below for detail. =item orderby Set column name to use for ordering. =item reverse Set 'true' or 'false'. The default is 'false'. =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#ListParameters> for details. =head2 row(\%condition) Returns first item of rows(\%condition) if available. =head2 add_row(\%contents) Creates new row and returns a Net::Google::Spreadsheets::Row object representing it. Arguments are contents of a row as a hashref. my $row = $ws->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); =head2 cells(\%args) Returns a list of Net::Google::Spreadsheets::Cell objects. Acceptable arguments are: =over 4 =item min-row =item max-row =item min-col =item max-col =item range =item return-empty =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#CellParameters> for details. =head2 cell(\%args) Returns Net::Google::Spreadsheets::Cell object. Arguments are: =over 4 =item col =item row =back =head2 batchupdate_cell(@args) update multiple cells with a batch request. Pass a list of hash references containing: =over 4 =item col =item row =item input_value =back =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/t/02_spreadsheet.t b/t/02_spreadsheet.t index a075493..beb7447 100644 --- a/t/02_spreadsheet.t +++ b/t/02_spreadsheet.t @@ -1,45 +1,47 @@ use t::Util; use Test::More; +use Test::Exception; ok my $service = service; { my @sheets = $service->spreadsheets; ok scalar @sheets; isa_ok $sheets[0], 'Net::Google::Spreadsheets::Spreadsheet'; ok $sheets[0]->title; ok $sheets[0]->key; ok $sheets[0]->etag; } { ok my $ss = spreadsheet; isa_ok $ss, 'Net::Google::Spreadsheets::Spreadsheet'; is $ss->title, $t::Util::SPREADSHEET_TITLE; like $ss->id, qr{^http://spreadsheets.google.com/feeds/spreadsheets/}; isa_ok $ss->author, 'XML::Atom::Person'; is $ss->author->email, config->{username}; my $key = $ss->key; ok length $key, 'key defined'; my $ss2 = $service->spreadsheet({key => $key}); ok $ss2; isa_ok $ss2, 'Net::Google::Spreadsheets::Spreadsheet'; is $ss2->key, $key; is $ss2->title, $t::Util::SPREADSHEET_TITLE; + throws_ok { $ss2->title('foobar') } qr{Cannot assign a value to a read-only accessor}; } { my @existing = map {$_->title} $service->spreadsheets; my $title; while (1) { $title = 'spreadsheet created at '.scalar localtime; grep {$_ eq $title} @existing or last; } my $ss = $service->spreadsheet({title => $title}); is $ss, undef, "spreadsheet named '$title' shouldn't exit"; my @ss = $service->spreadsheets({title => $title}); is scalar @ss, 0; } done_testing;
lopnor/Net-Google-Spreadsheets
17ce52e159e7282a6d92cf93d3e700aab16701c8
use $self->ns shortcut
diff --git a/lib/Net/Google/Spreadsheets/Cell.pm b/lib/Net/Google/Spreadsheets/Cell.pm index 4a559c2..d2046a6 100644 --- a/lib/Net/Google/Spreadsheets/Cell.pm +++ b/lib/Net/Google/Spreadsheets/Cell.pm @@ -1,122 +1,122 @@ package Net::Google::Spreadsheets::Cell; use Moose; use namespace::clean -except => 'meta'; use XML::Atom::Util qw(first); with 'Net::Google::DataAPI::Role::Entry'; has content => ( isa => 'Str', is => 'ro', ); has row => ( isa => 'Int', is => 'ro', ); has col => ( isa => 'Int', is => 'ro', ); has input_value => ( isa => 'Str', is => 'rw', trigger => sub {$_[0]->update}, ); after from_atom => sub { my ($self) = @_; - my $elem = first( $self->elem, $self->service->ns('gs')->{uri}, 'cell'); + my $elem = first( $self->elem, $self->ns('gs')->{uri}, 'cell'); $self->{row} = $elem->getAttribute('row'); $self->{col} = $elem->getAttribute('col'); $self->{input_value} = $elem->getAttribute('inputValue'); $self->{content} = $elem->textContent || ''; }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); - $entry->set($self->service->ns('gs'), 'cell', '', + $entry->set($self->ns('gs'), 'cell', '', { row => $self->row, col => $self->col, inputValue => $self->input_value, } ); my $link = XML::Atom::Link->new; $link->rel('edit'); $link->type('application/atom+xml'); $link->href($self->editurl); $entry->link($link); $entry->id($self->id); return $entry; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Cell - A representation class for Google Spreadsheet cell. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a cell my $cell = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->cell( { col => 1, row => 1, } ); # update a cell $cell->input_value('new value'); # get the content of a cell my $value = $cell->content; =head1 ATTRIBUTES =head2 input_value Rewritable attribute. You can set formula like '=A1+B1' or so. =head2 content Read only attribute. You can get the result of formula. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Record.pm b/lib/Net/Google/Spreadsheets/Record.pm index 5de68ee..2f932ab 100644 --- a/lib/Net/Google/Spreadsheets/Record.pm +++ b/lib/Net/Google/Spreadsheets/Record.pm @@ -1,117 +1,117 @@ package Net::Google::Spreadsheets::Record; use Moose; use namespace::clean -except => 'meta'; use XML::Atom::Util qw(nodelist); with 'Net::Google::DataAPI::Role::Entry', 'Net::Google::DataAPI::Role::HasContent'; after from_atom => sub { my ($self) = @_; - for my $node (nodelist($self->elem, $self->service->ns('gs')->{uri}, 'field')) { + for my $node (nodelist($self->elem, $self->ns('gs')->{uri}, 'field')) { $self->{content}->{$node->getAttribute('name')} = $node->textContent; } }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->{content}}) { - $entry->add($self->service->ns('gs'), 'field', $value, {name => $key}); + $entry->add($self->ns('gs'), 'field', $value, {name => $key}); } return $entry; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Record - A representation class for Google Spreadsheet record. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a record my $record = $service->spreadsheet( { title => 'list for new year cards', } )->table( { title => 'addressbook', } )->record( { sq => 'id = 1000', } ); # get the content of a row my $hashref = $record->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $record->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $record->param('name'); # returns 'Nobuo Danjou' my $newval = $record->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new record value (with all fields) my $hashref2 = $record->param; # same as $record->content; =head1 METHODS =head2 param sets and gets content value. =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Row> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Row.pm b/lib/Net/Google/Spreadsheets/Row.pm index aec004d..ebbdc96 100644 --- a/lib/Net/Google/Spreadsheets/Row.pm +++ b/lib/Net/Google/Spreadsheets/Row.pm @@ -1,155 +1,155 @@ package Net::Google::Spreadsheets::Row; use Moose; use namespace::clean -except => 'meta'; use Net::Google::DataAPI; use XML::Atom::Util qw(nodelist); with 'Net::Google::DataAPI::Role::Entry', 'Net::Google::DataAPI::Role::HasContent'; after from_atom => sub { my ($self) = @_; - for my $node (nodelist($self->elem, $self->service->ns('gsx')->{uri}, '*')) { + for my $node (nodelist($self->elem, $self->ns('gsx')->{uri}, '*')) { $self->{content}->{$node->localname} = $node->textContent; } }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->{content}}) { - $entry->set($self->service->ns('gsx'), $key, $value); + $entry->set($self->ns('gsx'), $key, $value); } return $entry; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Row - A representation class for Google Spreadsheet row. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a row my $row = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->row( { sq => 'id = 1000' } ); # get the content of a row my $hashref = $row->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $row->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $row->param('name'); # returns 'Nobuo Danjou' my $newval = $row->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new row value (with all fields) my $hashref2 = $row->param; # same as $row->content; =head1 METHODS =head2 param sets and gets content value. =head1 CAVEATS Space characters in hash key of rows will be removed when you access rows. See below. my $ws = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'})->worksheet(1); $ws->batchupdate_cell( {col => 1,row => 1, input_value => 'name'}, {col => 2,row => 1, input_value => 'mail address'}, ); $ws->add_row( { name => 'my name', mailaddress => '[email protected]', # above passes, below fails. # 'mail address' => '[email protected]', } ); Instead, Net::Google::Spreadsheets::Table and Net::Google::Spreadsheets::Record allows space characters in column name. my $s = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'}); my $t = $s->add_table( { worksheet => $s->worksheet(1), columns => ['name', 'mail address'], } ); $t->add_record( { name => 'my name', 'mail address' => '[email protected]', } ); =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Table.pm b/lib/Net/Google/Spreadsheets/Table.pm index e832710..bed38df 100644 --- a/lib/Net/Google/Spreadsheets/Table.pm +++ b/lib/Net/Google/Spreadsheets/Table.pm @@ -1,228 +1,228 @@ package Net::Google::Spreadsheets::Table; use Moose; use Moose::Util::TypeConstraints; use namespace::clean -except => 'meta'; use Net::Google::DataAPI; use XML::Atom::Util qw(nodelist first create_element); with 'Net::Google::DataAPI::Role::Entry'; subtype 'ColumnList' => as 'ArrayRef[Net::Google::Spreadsheets::Table::Column]'; coerce 'ColumnList' => from 'ArrayRef[HashRef]' => via { [ map {Net::Google::Spreadsheets::Table::Column->new($_)} @$_ ] }; coerce 'ColumnList' => from 'ArrayRef[Str]' => via { my @c; my $index = 0; for my $value (@$_) { push @c, Net::Google::Spreadsheets::Table::Column->new( index => ++$index, name => $value, ); } \@c; }; coerce 'ColumnList' => from 'HashRef' => via { my @c; while (my ($key, $value) = each(%$_)) { push @c, Net::Google::Spreadsheets::Table::Column->new( index => $key, name => $value, ); } \@c; }; subtype 'WorksheetName' => as 'Str'; coerce 'WorksheetName' => from 'Net::Google::Spreadsheets::Worksheet' => via { $_->title }; feedurl record => ( entry_class => 'Net::Google::Spreadsheets::Record', arg_builder => sub { my ($self, $args) = @_; return {content => $args}; }, as_content_src => 1, ); has summary => ( is => 'rw', isa => 'Str' ); has worksheet => ( is => 'ro', isa => 'WorksheetName', coerce => 1 ); has header => ( is => 'ro', isa => 'Int', required => 1, default => 1 ); has start_row => ( is => 'ro', isa => 'Int', required => 1, default => 2 ); has num_rows => ( is => 'ro', isa => 'Int' ); has columns => ( is => 'ro', isa => 'ColumnList', coerce => 1 ); has insertion_mode => ( is => 'ro', isa => (enum ['insert', 'overwrite']), default => 'overwrite' ); after from_atom => sub { my ($self) = @_; - my $gsns = $self->service->ns('gs')->{uri}; + my $gsns = $self->ns('gs')->{uri}; my $elem = $self->elem; $self->{summary} = $self->atom->summary; $self->{worksheet} = first( $elem, $gsns, 'worksheet')->getAttribute('name'); $self->{header} = first( $elem, $gsns, 'header')->getAttribute('row'); my @columns; my $data = first($elem, $gsns, 'data'); $self->{insertion_mode} = $data->getAttribute('insertionMode'); $self->{start_row} = $data->getAttribute('startRow'); $self->{num_rows} = $data->getAttribute('numRows'); for (nodelist($data, $gsns, 'column')) { push @columns, Net::Google::Spreadsheets::Table::Column->new( index => $_->getAttribute('index'), name => $_->getAttribute('name'), ); } $self->{columns} = \@columns; }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); - my $gsns = $self->service->ns('gs')->{uri}; + my $gsns = $self->ns('gs')->{uri}; $entry->summary($self->summary) if $self->summary; $entry->set($gsns, 'worksheet', '', {name => $self->worksheet}); $entry->set($gsns, 'header', '', {row => $self->header}); my $data = create_element($gsns, 'data'); $data->setAttribute(startRow => $self->start_row); $data->setAttribute(insertionMode => $self->insertion_mode); $data->setAttribute(startRow => $self->start_row) if $self->start_row; for ( @{$self->columns} ) { my $column = create_element($gsns, 'column'); $column->setAttribute(index => $_->index); $column->setAttribute(name => $_->name); $data->appendChild($column); } $entry->set($gsns, 'data', $data); return $entry; }; __PACKAGE__->meta->make_immutable; package # hide from PAUSE Net::Google::Spreadsheets::Table::Column; use Moose; has 'index' => ( is => 'ro', isa => 'Str' ); has 'name' => ( is => 'ro', isa => 'Str' ); __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Table - A representation class for Google Spreadsheet table. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a table my $table = $service->spreadsheet( { title => 'list for new year cards', } )->table( { title => 'sample table', } ); # create a record my $r = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # get records my @records = $table->records; # search records @records = $table->records({sq => 'age > 20'}); # search a record my $record = $table->record({sq => 'name = "Nobuo Danjou"'}); =head1 METHODS =head2 records(\%condition) Returns a list of Net::Google::Spreadsheets::Record objects. Acceptable arguments are: =over 4 =item sq Structured query on the full text in the worksheet. see the URL below for detail. =item orderby Set column name to use for ordering. =item reverse Set 'true' or 'false'. The default is 'false'. =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#RecordParameters> for details. =head2 record(\%condition) Returns first item of records(\%condition) if available. =head2 add_record(\%contents) Creates new record and returns a Net::Google::Spreadsheets::Record object representing it. Arguments are contents of a row as a hashref. my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Record> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Worksheet.pm b/lib/Net/Google/Spreadsheets/Worksheet.pm index b4d6fc6..5ff1d31 100644 --- a/lib/Net/Google/Spreadsheets/Worksheet.pm +++ b/lib/Net/Google/Spreadsheets/Worksheet.pm @@ -1,259 +1,259 @@ package Net::Google::Spreadsheets::Worksheet; use Moose; use namespace::clean -except => 'meta'; use Net::Google::DataAPI; with 'Net::Google::DataAPI::Role::Entry'; use Carp; use Net::Google::Spreadsheets::Cell; use XML::Atom::Util qw(first); feedurl row => ( entry_class => 'Net::Google::Spreadsheets::Row', as_content_src => 1, arg_builder => sub { my ($self, $args) = @_; return {content => $args}; }, ); feedurl cell => ( entry_class => 'Net::Google::Spreadsheets::Cell', can_add => 0, rel => 'http://schemas.google.com/spreadsheets/2006#cellsfeed', query_builder => sub { my ($self, $args) = @_; if (my $col = delete $args->{col}) { $args->{'max-col'} = $col; $args->{'min-col'} = $col; $args->{'return-empty'} = 'true'; } if (my $row = delete $args->{row}) { $args->{'max-row'} = $row; $args->{'min-row'} = $row; $args->{'return-empty'} = 'true'; } return $args; }, ); has row_count => ( isa => 'Int', is => 'rw', default => 100, trigger => sub {$_[0]->update} ); has col_count => ( isa => 'Int', is => 'rw', default => 20, trigger => sub {$_[0]->update} ); around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); - $entry->set($self->service->ns('gs'), 'rowCount', $self->row_count); - $entry->set($self->service->ns('gs'), 'colCount', $self->col_count); + $entry->set($self->ns('gs'), 'rowCount', $self->row_count); + $entry->set($self->ns('gs'), 'colCount', $self->col_count); return $entry; }; after from_atom => sub { my ($self) = @_; - $self->{row_count} = $self->atom->get($self->service->ns('gs'), 'rowCount'); - $self->{col_count} = $self->atom->get($self->service->ns('gs'), 'colCount'); + $self->{row_count} = $self->atom->get($self->ns('gs'), 'rowCount'); + $self->{col_count} = $self->atom->get($self->ns('gs'), 'colCount'); }; __PACKAGE__->meta->make_immutable; sub batchupdate_cell { my ($self, @args) = @_; my $feed = XML::Atom::Feed->new; for ( @args ) { my $id = sprintf("%s/R%sC%s",$self->cell_feedurl, $_->{row}, $_->{col}); $_->{id} = $_->{editurl} = $id; $_->{container} = $self, my $entry = Net::Google::Spreadsheets::Cell->new($_)->to_atom; - $entry->set($self->service->ns('batch'), operation => '', {type => 'update'}); - $entry->set($self->service->ns('batch'), id => $id); + $entry->set($self->ns('batch'), operation => '', {type => 'update'}); + $entry->set($self->ns('batch'), id => $id); $feed->add_entry($entry); } my $res_feed = $self->service->post( $self->cell_feedurl."/batch", $feed, {'If-Match' => '*'} ); $self->sync; return map { Net::Google::Spreadsheets::Cell->new( atom => $_, container => $self, ) } grep { my $node = first( - $_->elem, $self->service->ns('batch')->{uri}, 'status' + $_->elem, $self->ns('batch')->{uri}, 'status' ); $node->getAttribute('code') == 200; } $res_feed->entries; } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Worksheet - Representation of worksheet. =head1 SYNOPSIS my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); my $ss = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); my $worksheet = $ss->worksheet({title => 'Sheet1'}); # update cell by batch request $worksheet->batchupdate_cell( {col => 1, row => 1, input_value => 'name'}, {col => 2, row => 1, input_value => 'nick'}, {col => 3, row => 1, input_value => 'mail'}, {col => 4, row => 1, input_value => 'age'}, ); # get a cell object my $cell = $worksheet->cell({col => 1, row => 1}); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # get rows my @rows = $worksheet->rows; # search rows @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); =head1 METHODS =head2 rows(\%condition) Returns a list of Net::Google::Spreadsheets::Row objects. Acceptable arguments are: =over 4 =item sq Structured query on the full text in the worksheet. see the URL below for detail. =item orderby Set column name to use for ordering. =item reverse Set 'true' or 'false'. The default is 'false'. =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#ListParameters> for details. =head2 row(\%condition) Returns first item of rows(\%condition) if available. =head2 add_row(\%contents) Creates new row and returns a Net::Google::Spreadsheets::Row object representing it. Arguments are contents of a row as a hashref. my $row = $ws->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); =head2 cells(\%args) Returns a list of Net::Google::Spreadsheets::Cell objects. Acceptable arguments are: =over 4 =item min-row =item max-row =item min-col =item max-col =item range =item return-empty =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#CellParameters> for details. =head2 cell(\%args) Returns Net::Google::Spreadsheets::Cell object. Arguments are: =over 4 =item col =item row =back =head2 batchupdate_cell(@args) update multiple cells with a batch request. Pass a list of hash references containing: =over 4 =item col =item row =item input_value =back =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut
lopnor/Net-Google-Spreadsheets
d7607eb45ac54ba5b138ce5cc08db2156e66efac
Now uses Net::Google::DataAPI
diff --git a/MANIFEST b/MANIFEST index 630928c..ec3adf2 100644 --- a/MANIFEST +++ b/MANIFEST @@ -1,52 +1,48 @@ Changes inc/Module/Install.pm inc/Module/Install/AuthorTests.pm inc/Module/Install/Base.pm inc/Module/Install/Can.pm inc/Module/Install/Fetch.pm inc/Module/Install/Include.pm inc/Module/Install/Makefile.pm inc/Module/Install/Metadata.pm +inc/Module/Install/Repository.pm inc/Module/Install/TestBase.pm inc/Module/Install/Win32.pm inc/Module/Install/WriteAll.pm inc/Spiffy.pm inc/Test/Base.pm inc/Test/Base/Filter.pm inc/Test/Builder.pm inc/Test/Builder/Module.pm inc/Test/Exception.pm inc/Test/MockModule.pm inc/Test/MockObject.pm inc/Test/More.pm lib/Net/Google/Spreadsheets.pm lib/Net/Google/Spreadsheets/Cell.pm lib/Net/Google/Spreadsheets/Record.pm -lib/Net/Google/Spreadsheets/Role/Base.pm -lib/Net/Google/Spreadsheets/Role/HasContent.pm -lib/Net/Google/Spreadsheets/Role/Service.pm lib/Net/Google/Spreadsheets/Row.pm lib/Net/Google/Spreadsheets/Spreadsheet.pm lib/Net/Google/Spreadsheets/Table.pm -lib/Net/Google/Spreadsheets/Traits/Feed.pm -lib/Net/Google/Spreadsheets/UserAgent.pm lib/Net/Google/Spreadsheets/Worksheet.pm Makefile.PL MANIFEST This list of files META.yml README t/00_compile.t t/01_instanciate.t t/02_spreadsheet.t t/03_worksheet.t t/04_cell.t t/05_row.t t/06_table.t t/07_record.t t/08_error.t t/Util.pm xt/01_podspell.t xt/02_perlcritic.t xt/03_pod.t xt/04_synopsis.t xt/perlcriticrc diff --git a/Makefile.PL b/Makefile.PL index db0ad95..b54d9ea 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,25 +1,22 @@ use inc::Module::Install; name 'Net-Google-Spreadsheets'; all_from 'lib/Net/Google/Spreadsheets.pm'; requires 'Carp'; requires 'XML::Atom'; -requires 'Net::Google::AuthSub'; -requires 'Crypt::SSLeay'; -requires 'LWP::UserAgent'; -requires 'URI'; requires 'Moose' => 0.34; -requires 'MooseX::Role::Parameterized'; +requires 'Net::Google::DataAPI'; +requires 'URI'; requires 'Path::Class'; -tests 't/*.t'; +tests_recursive; author_tests 'xt'; build_requires 'Test::More' => '0.88'; build_requires 'Test::Exception'; build_requires 'Test::MockModule'; build_requires 'Test::MockObject'; use_test_base; auto_include; auto_set_repository; WriteAll; diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index 620e253..b35edd7 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,272 +1,272 @@ package Net::Google::Spreadsheets; use Moose; -use Net::Google::GData; +use Net::Google::DataAPI; use namespace::clean -except => 'meta'; use 5.008001; our $VERSION = '0.06'; -with 'Net::Google::GData::Role::Service' => { +with 'Net::Google::DataAPI::Role::Service' => { service => 'wise', source => __PACKAGE__.'-'.$VERSION, ns => { gs => 'http://schemas.google.com/spreadsheets/2006', gsx => 'http://schemas.google.com/spreadsheets/2006/extended', batch => 'http://schemas.google.com/gdata/batch', } }; feedurl spreadsheet => ( default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full', entry_class => 'Net::Google::Spreadsheets::Spreadsheet', can_add => 0, ); __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, {row => 1, col => 4, input_value => 'age'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # fetch rows my @rows = $worksheet->rows; # or fetch rows with query @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); # delete the row $row->delete; # delete the worksheet $worksheet->delete; # create a table my $table = $spreadsheet->add_table( { worksheet => $new_worksheet, columns => ['name', 'nick', 'mail address', 'age'], } ); # add a record my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', 'mail address' => '[email protected]', age => '33', } ); # find a record my $found = $table->record( { sq => '"mail address" = "[email protected]"' } ); # delete it $found->delete; # delete table $table->delete; =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 4 =item username Username for Google. This should be full email address format like '[email protected]'. =item password Password corresponding to the username. =item source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 4 =item title title of the spreadsheet. =item title-exact whether title search should match exactly or not. =item key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 TESTING To test this module, you have to prepare as below. =over 4 =item create a spreadsheet by hand Go to L<http://docs.google.com> and create a spreadsheet. =item set SPREADSHEET_TITLE environment variable export SPREADSHEET_TITLE='my test spreadsheet' or so. =item set username and password for google.com via Config::Pit install Config::Pit and type ppit set google.com then some editor comes up and type your username and password like --- username: [email protected] password: foobarbaz =item run tests as always, perl Makefile.PL make make test =back =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Record> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Net/Google/Spreadsheets/Cell.pm b/lib/Net/Google/Spreadsheets/Cell.pm index d5e9139..4a559c2 100644 --- a/lib/Net/Google/Spreadsheets/Cell.pm +++ b/lib/Net/Google/Spreadsheets/Cell.pm @@ -1,122 +1,122 @@ package Net::Google::Spreadsheets::Cell; use Moose; use namespace::clean -except => 'meta'; use XML::Atom::Util qw(first); -with 'Net::Google::GData::Role::Entry'; +with 'Net::Google::DataAPI::Role::Entry'; has content => ( isa => 'Str', is => 'ro', ); has row => ( isa => 'Int', is => 'ro', ); has col => ( isa => 'Int', is => 'ro', ); has input_value => ( isa => 'Str', is => 'rw', trigger => sub {$_[0]->update}, ); after from_atom => sub { my ($self) = @_; my $elem = first( $self->elem, $self->service->ns('gs')->{uri}, 'cell'); $self->{row} = $elem->getAttribute('row'); $self->{col} = $elem->getAttribute('col'); $self->{input_value} = $elem->getAttribute('inputValue'); $self->{content} = $elem->textContent || ''; }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->service->ns('gs'), 'cell', '', { row => $self->row, col => $self->col, inputValue => $self->input_value, } ); my $link = XML::Atom::Link->new; $link->rel('edit'); $link->type('application/atom+xml'); $link->href($self->editurl); $entry->link($link); $entry->id($self->id); return $entry; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Cell - A representation class for Google Spreadsheet cell. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a cell my $cell = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->cell( { col => 1, row => 1, } ); # update a cell $cell->input_value('new value'); # get the content of a cell my $value = $cell->content; =head1 ATTRIBUTES =head2 input_value Rewritable attribute. You can set formula like '=A1+B1' or so. =head2 content Read only attribute. You can get the result of formula. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Record.pm b/lib/Net/Google/Spreadsheets/Record.pm index 0b6dac7..5de68ee 100644 --- a/lib/Net/Google/Spreadsheets/Record.pm +++ b/lib/Net/Google/Spreadsheets/Record.pm @@ -1,117 +1,117 @@ package Net::Google::Spreadsheets::Record; use Moose; use namespace::clean -except => 'meta'; use XML::Atom::Util qw(nodelist); with - 'Net::Google::GData::Role::Entry', - 'Net::Google::GData::Role::HasContent'; + 'Net::Google::DataAPI::Role::Entry', + 'Net::Google::DataAPI::Role::HasContent'; after from_atom => sub { my ($self) = @_; for my $node (nodelist($self->elem, $self->service->ns('gs')->{uri}, 'field')) { $self->{content}->{$node->getAttribute('name')} = $node->textContent; } }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->{content}}) { $entry->add($self->service->ns('gs'), 'field', $value, {name => $key}); } return $entry; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Record - A representation class for Google Spreadsheet record. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a record my $record = $service->spreadsheet( { title => 'list for new year cards', } )->table( { title => 'addressbook', } )->record( { sq => 'id = 1000', } ); # get the content of a row my $hashref = $record->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $record->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $record->param('name'); # returns 'Nobuo Danjou' my $newval = $record->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new record value (with all fields) my $hashref2 = $record->param; # same as $record->content; =head1 METHODS =head2 param sets and gets content value. =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Row> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Row.pm b/lib/Net/Google/Spreadsheets/Row.pm index 98dfb90..aec004d 100644 --- a/lib/Net/Google/Spreadsheets/Row.pm +++ b/lib/Net/Google/Spreadsheets/Row.pm @@ -1,155 +1,155 @@ package Net::Google::Spreadsheets::Row; use Moose; use namespace::clean -except => 'meta'; -use Net::Google::GData; +use Net::Google::DataAPI; use XML::Atom::Util qw(nodelist); with - 'Net::Google::GData::Role::Entry', - 'Net::Google::GData::Role::HasContent'; + 'Net::Google::DataAPI::Role::Entry', + 'Net::Google::DataAPI::Role::HasContent'; after from_atom => sub { my ($self) = @_; for my $node (nodelist($self->elem, $self->service->ns('gsx')->{uri}, '*')) { $self->{content}->{$node->localname} = $node->textContent; } }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->{content}}) { $entry->set($self->service->ns('gsx'), $key, $value); } return $entry; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Row - A representation class for Google Spreadsheet row. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a row my $row = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->row( { sq => 'id = 1000' } ); # get the content of a row my $hashref = $row->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $row->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $row->param('name'); # returns 'Nobuo Danjou' my $newval = $row->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new row value (with all fields) my $hashref2 = $row->param; # same as $row->content; =head1 METHODS =head2 param sets and gets content value. =head1 CAVEATS Space characters in hash key of rows will be removed when you access rows. See below. my $ws = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'})->worksheet(1); $ws->batchupdate_cell( {col => 1,row => 1, input_value => 'name'}, {col => 2,row => 1, input_value => 'mail address'}, ); $ws->add_row( { name => 'my name', mailaddress => '[email protected]', # above passes, below fails. # 'mail address' => '[email protected]', } ); Instead, Net::Google::Spreadsheets::Table and Net::Google::Spreadsheets::Record allows space characters in column name. my $s = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'}); my $t = $s->add_table( { worksheet => $s->worksheet(1), columns => ['name', 'mail address'], } ); $t->add_record( { name => 'my name', 'mail address' => '[email protected]', } ); =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Spreadsheet.pm b/lib/Net/Google/Spreadsheets/Spreadsheet.pm index e141475..eb54614 100644 --- a/lib/Net/Google/Spreadsheets/Spreadsheet.pm +++ b/lib/Net/Google/Spreadsheets/Spreadsheet.pm @@ -1,231 +1,231 @@ package Net::Google::Spreadsheets::Spreadsheet; use Moose; use namespace::clean -except => 'meta'; -use Net::Google::GData; +use Net::Google::DataAPI; -with 'Net::Google::GData::Role::Entry'; +with 'Net::Google::DataAPI::Role::Entry'; use Path::Class; use URI; has +title => ( is => 'ro', ); has key => ( isa => 'Str', is => 'ro', ); feedurl worksheet => ( entry_class => 'Net::Google::Spreadsheets::Worksheet', as_content_src => 1, ); feedurl table => ( entry_class => 'Net::Google::Spreadsheets::Table', rel => 'http://schemas.google.com/spreadsheets/2006#tablesfeed', ); after from_atom => sub { my ($self) = @_; $self->{key} = file(URI->new($self->id)->path)->basename; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Spreadsheet - Representation of spreadsheet. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # create a worksheet my $worksheet = $spreadsheet->add_worksheet( { title => 'foobar', col_count => 10, row_count => 100, } ); # list worksheets my @ws = $spreadsheet->worksheets; # find a worksheet my $ws = $spreadsheet->worksheet({title => 'fooba'}); # create a table my $table = $spreadsheet->add_table( { title => 'sample table', worksheet => $worksheet, columns => ['id', 'username', 'mail', 'password'], } ); # list tables my @t = $spreadsheet->tables; # find a worksheet my $t = $spreadsheet->table({title => 'sample table'}); =head1 METHODS =head2 worksheets(\%condition) Returns a list of Net::Google::Spreadsheets::Worksheet objects. Acceptable arguments are: =over 4 =item title =item title-exact =back =head2 worksheet(\%condition) Returns first item of worksheets(\%condition) if available. =head2 add_worksheet(\%attribuets) Creates new worksheet and returns a Net::Google::Spreadsheets::Worksheet object representing it. Arguments (all optional) are: =over 4 =item title =item col_count =item row_count =back =head2 tables(\%condition) Returns a list of Net::Google::Spreadsheets::Table objects. Acceptable arguments are: =over 4 =item title =item title-exact =back =head2 table(\%condition) Returns first item of tables(\%condition) if available. =head2 add_table(\%attribuets) Creates new table and returns a Net::Google::Spreadsheets::Table object representing it. Arguments are: =over 4 =item title (optional) =item summary (optional) =item worksheet Worksheet where the table lives. worksheet instance or the title. =item header (optional, default = 1) Row number of header =item start_row (optional, default = 2) The index of the first row of the data section. =item insertion_mode (optional, default = 'overwrite') Insertion mode. 'insert' inserts new row into the worksheet when creating record, 'overwrite' tries to use existing rows in the worksheet. =item columns Columns of the table. you can specify them as hashref, arrayref, arrayref of hashref. $ss->add_table( { worksheet => $ws, columns => [ {index => 1, name => 'foo'}, {index => 2, name => 'bar'}, {index => 3, name => 'baz'}, ], } ); $ss->add_table( { worksheet => $ws, columns => { A => 'foo', B => 'bar', C => 'baz', } } ); $ss->add_table( { worksheet => $ws, columns => ['foo', 'bar', 'baz'], } ); 'index' of the first case and hash key of the second case is column index of the worksheet. In the third case, the columns is automatically placed to the columns of the worksheet from 'A' to 'Z' order. =back =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Table> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Table.pm b/lib/Net/Google/Spreadsheets/Table.pm index fb1da19..e832710 100644 --- a/lib/Net/Google/Spreadsheets/Table.pm +++ b/lib/Net/Google/Spreadsheets/Table.pm @@ -1,228 +1,228 @@ package Net::Google::Spreadsheets::Table; use Moose; use Moose::Util::TypeConstraints; use namespace::clean -except => 'meta'; -use Net::Google::GData; +use Net::Google::DataAPI; use XML::Atom::Util qw(nodelist first create_element); -with 'Net::Google::GData::Role::Entry'; +with 'Net::Google::DataAPI::Role::Entry'; subtype 'ColumnList' => as 'ArrayRef[Net::Google::Spreadsheets::Table::Column]'; coerce 'ColumnList' => from 'ArrayRef[HashRef]' => via { [ map {Net::Google::Spreadsheets::Table::Column->new($_)} @$_ ] }; coerce 'ColumnList' => from 'ArrayRef[Str]' => via { my @c; my $index = 0; for my $value (@$_) { push @c, Net::Google::Spreadsheets::Table::Column->new( index => ++$index, name => $value, ); } \@c; }; coerce 'ColumnList' => from 'HashRef' => via { my @c; while (my ($key, $value) = each(%$_)) { push @c, Net::Google::Spreadsheets::Table::Column->new( index => $key, name => $value, ); } \@c; }; subtype 'WorksheetName' => as 'Str'; coerce 'WorksheetName' => from 'Net::Google::Spreadsheets::Worksheet' => via { $_->title }; feedurl record => ( entry_class => 'Net::Google::Spreadsheets::Record', arg_builder => sub { my ($self, $args) = @_; return {content => $args}; }, as_content_src => 1, ); has summary => ( is => 'rw', isa => 'Str' ); has worksheet => ( is => 'ro', isa => 'WorksheetName', coerce => 1 ); has header => ( is => 'ro', isa => 'Int', required => 1, default => 1 ); has start_row => ( is => 'ro', isa => 'Int', required => 1, default => 2 ); has num_rows => ( is => 'ro', isa => 'Int' ); has columns => ( is => 'ro', isa => 'ColumnList', coerce => 1 ); has insertion_mode => ( is => 'ro', isa => (enum ['insert', 'overwrite']), default => 'overwrite' ); after from_atom => sub { my ($self) = @_; my $gsns = $self->service->ns('gs')->{uri}; my $elem = $self->elem; $self->{summary} = $self->atom->summary; $self->{worksheet} = first( $elem, $gsns, 'worksheet')->getAttribute('name'); $self->{header} = first( $elem, $gsns, 'header')->getAttribute('row'); my @columns; my $data = first($elem, $gsns, 'data'); $self->{insertion_mode} = $data->getAttribute('insertionMode'); $self->{start_row} = $data->getAttribute('startRow'); $self->{num_rows} = $data->getAttribute('numRows'); for (nodelist($data, $gsns, 'column')) { push @columns, Net::Google::Spreadsheets::Table::Column->new( index => $_->getAttribute('index'), name => $_->getAttribute('name'), ); } $self->{columns} = \@columns; }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); my $gsns = $self->service->ns('gs')->{uri}; $entry->summary($self->summary) if $self->summary; $entry->set($gsns, 'worksheet', '', {name => $self->worksheet}); $entry->set($gsns, 'header', '', {row => $self->header}); my $data = create_element($gsns, 'data'); $data->setAttribute(startRow => $self->start_row); $data->setAttribute(insertionMode => $self->insertion_mode); $data->setAttribute(startRow => $self->start_row) if $self->start_row; for ( @{$self->columns} ) { my $column = create_element($gsns, 'column'); $column->setAttribute(index => $_->index); $column->setAttribute(name => $_->name); $data->appendChild($column); } $entry->set($gsns, 'data', $data); return $entry; }; __PACKAGE__->meta->make_immutable; package # hide from PAUSE Net::Google::Spreadsheets::Table::Column; use Moose; has 'index' => ( is => 'ro', isa => 'Str' ); has 'name' => ( is => 'ro', isa => 'Str' ); __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Table - A representation class for Google Spreadsheet table. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a table my $table = $service->spreadsheet( { title => 'list for new year cards', } )->table( { title => 'sample table', } ); # create a record my $r = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # get records my @records = $table->records; # search records @records = $table->records({sq => 'age > 20'}); # search a record my $record = $table->record({sq => 'name = "Nobuo Danjou"'}); =head1 METHODS =head2 records(\%condition) Returns a list of Net::Google::Spreadsheets::Record objects. Acceptable arguments are: =over 4 =item sq Structured query on the full text in the worksheet. see the URL below for detail. =item orderby Set column name to use for ordering. =item reverse Set 'true' or 'false'. The default is 'false'. =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#RecordParameters> for details. =head2 record(\%condition) Returns first item of records(\%condition) if available. =head2 add_record(\%contents) Creates new record and returns a Net::Google::Spreadsheets::Record object representing it. Arguments are contents of a row as a hashref. my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Record> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Worksheet.pm b/lib/Net/Google/Spreadsheets/Worksheet.pm index a556bfd..b4d6fc6 100644 --- a/lib/Net/Google/Spreadsheets/Worksheet.pm +++ b/lib/Net/Google/Spreadsheets/Worksheet.pm @@ -1,259 +1,259 @@ package Net::Google::Spreadsheets::Worksheet; use Moose; use namespace::clean -except => 'meta'; -use Net::Google::GData; +use Net::Google::DataAPI; -with 'Net::Google::GData::Role::Entry'; +with 'Net::Google::DataAPI::Role::Entry'; use Carp; use Net::Google::Spreadsheets::Cell; use XML::Atom::Util qw(first); feedurl row => ( entry_class => 'Net::Google::Spreadsheets::Row', as_content_src => 1, arg_builder => sub { my ($self, $args) = @_; return {content => $args}; }, ); feedurl cell => ( entry_class => 'Net::Google::Spreadsheets::Cell', can_add => 0, rel => 'http://schemas.google.com/spreadsheets/2006#cellsfeed', query_builder => sub { my ($self, $args) = @_; if (my $col = delete $args->{col}) { $args->{'max-col'} = $col; $args->{'min-col'} = $col; $args->{'return-empty'} = 'true'; } if (my $row = delete $args->{row}) { $args->{'max-row'} = $row; $args->{'min-row'} = $row; $args->{'return-empty'} = 'true'; } return $args; }, ); has row_count => ( isa => 'Int', is => 'rw', default => 100, trigger => sub {$_[0]->update} ); has col_count => ( isa => 'Int', is => 'rw', default => 20, trigger => sub {$_[0]->update} ); around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->service->ns('gs'), 'rowCount', $self->row_count); $entry->set($self->service->ns('gs'), 'colCount', $self->col_count); return $entry; }; after from_atom => sub { my ($self) = @_; $self->{row_count} = $self->atom->get($self->service->ns('gs'), 'rowCount'); $self->{col_count} = $self->atom->get($self->service->ns('gs'), 'colCount'); }; __PACKAGE__->meta->make_immutable; sub batchupdate_cell { my ($self, @args) = @_; my $feed = XML::Atom::Feed->new; for ( @args ) { my $id = sprintf("%s/R%sC%s",$self->cell_feedurl, $_->{row}, $_->{col}); $_->{id} = $_->{editurl} = $id; $_->{container} = $self, my $entry = Net::Google::Spreadsheets::Cell->new($_)->to_atom; $entry->set($self->service->ns('batch'), operation => '', {type => 'update'}); $entry->set($self->service->ns('batch'), id => $id); $feed->add_entry($entry); } my $res_feed = $self->service->post( $self->cell_feedurl."/batch", $feed, {'If-Match' => '*'} ); $self->sync; return map { Net::Google::Spreadsheets::Cell->new( atom => $_, container => $self, ) } grep { my $node = first( $_->elem, $self->service->ns('batch')->{uri}, 'status' ); $node->getAttribute('code') == 200; } $res_feed->entries; } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Worksheet - Representation of worksheet. =head1 SYNOPSIS my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); my $ss = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); my $worksheet = $ss->worksheet({title => 'Sheet1'}); # update cell by batch request $worksheet->batchupdate_cell( {col => 1, row => 1, input_value => 'name'}, {col => 2, row => 1, input_value => 'nick'}, {col => 3, row => 1, input_value => 'mail'}, {col => 4, row => 1, input_value => 'age'}, ); # get a cell object my $cell = $worksheet->cell({col => 1, row => 1}); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # get rows my @rows = $worksheet->rows; # search rows @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); =head1 METHODS =head2 rows(\%condition) Returns a list of Net::Google::Spreadsheets::Row objects. Acceptable arguments are: =over 4 =item sq Structured query on the full text in the worksheet. see the URL below for detail. =item orderby Set column name to use for ordering. =item reverse Set 'true' or 'false'. The default is 'false'. =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#ListParameters> for details. =head2 row(\%condition) Returns first item of rows(\%condition) if available. =head2 add_row(\%contents) Creates new row and returns a Net::Google::Spreadsheets::Row object representing it. Arguments are contents of a row as a hashref. my $row = $ws->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); =head2 cells(\%args) Returns a list of Net::Google::Spreadsheets::Cell objects. Acceptable arguments are: =over 4 =item min-row =item max-row =item min-col =item max-col =item range =item return-empty =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#CellParameters> for details. =head2 cell(\%args) Returns Net::Google::Spreadsheets::Cell object. Arguments are: =over 4 =item col =item row =back =head2 batchupdate_cell(@args) update multiple cells with a batch request. Pass a list of hash references containing: =over 4 =item col =item row =item input_value =back =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut
lopnor/Net-Google-Spreadsheets
d6062b16913442caad2814b052cedfa37f55ecba
moved all
diff --git a/lib/Net/Google/Spreadsheets/Cell.pm b/lib/Net/Google/Spreadsheets/Cell.pm index a379b9c..d5e9139 100644 --- a/lib/Net/Google/Spreadsheets/Cell.pm +++ b/lib/Net/Google/Spreadsheets/Cell.pm @@ -1,122 +1,122 @@ package Net::Google::Spreadsheets::Cell; use Moose; use namespace::clean -except => 'meta'; use XML::Atom::Util qw(first); -with 'Net::Google::Spreadsheets::Role::Base'; +with 'Net::Google::GData::Role::Entry'; has content => ( isa => 'Str', is => 'ro', ); has row => ( isa => 'Int', is => 'ro', ); has col => ( isa => 'Int', is => 'ro', ); has input_value => ( isa => 'Str', is => 'rw', trigger => sub {$_[0]->update}, ); after from_atom => sub { my ($self) = @_; - my $elem = first( $self->elem, $self->gsns->{uri}, 'cell'); + my $elem = first( $self->elem, $self->service->ns('gs')->{uri}, 'cell'); $self->{row} = $elem->getAttribute('row'); $self->{col} = $elem->getAttribute('col'); $self->{input_value} = $elem->getAttribute('inputValue'); $self->{content} = $elem->textContent || ''; }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); - $entry->set($self->gsns, 'cell', '', + $entry->set($self->service->ns('gs'), 'cell', '', { row => $self->row, col => $self->col, inputValue => $self->input_value, } ); my $link = XML::Atom::Link->new; $link->rel('edit'); $link->type('application/atom+xml'); $link->href($self->editurl); $entry->link($link); $entry->id($self->id); return $entry; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Cell - A representation class for Google Spreadsheet cell. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a cell my $cell = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->cell( { col => 1, row => 1, } ); # update a cell $cell->input_value('new value'); # get the content of a cell my $value = $cell->content; =head1 ATTRIBUTES =head2 input_value Rewritable attribute. You can set formula like '=A1+B1' or so. =head2 content Read only attribute. You can get the result of formula. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Record.pm b/lib/Net/Google/Spreadsheets/Record.pm index b481b01..0b6dac7 100644 --- a/lib/Net/Google/Spreadsheets/Record.pm +++ b/lib/Net/Google/Spreadsheets/Record.pm @@ -1,117 +1,117 @@ package Net::Google::Spreadsheets::Record; use Moose; use namespace::clean -except => 'meta'; use XML::Atom::Util qw(nodelist); with - 'Net::Google::Spreadsheets::Role::Base', - 'Net::Google::Spreadsheets::Role::HasContent'; + 'Net::Google::GData::Role::Entry', + 'Net::Google::GData::Role::HasContent'; after from_atom => sub { my ($self) = @_; - for my $node (nodelist($self->elem, $self->gsns->{uri}, 'field')) { + for my $node (nodelist($self->elem, $self->service->ns('gs')->{uri}, 'field')) { $self->{content}->{$node->getAttribute('name')} = $node->textContent; } }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->{content}}) { - $entry->add($self->gsns, 'field', $value, {name => $key}); + $entry->add($self->service->ns('gs'), 'field', $value, {name => $key}); } return $entry; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Record - A representation class for Google Spreadsheet record. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a record my $record = $service->spreadsheet( { title => 'list for new year cards', } )->table( { title => 'addressbook', } )->record( { sq => 'id = 1000', } ); # get the content of a row my $hashref = $record->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $record->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $record->param('name'); # returns 'Nobuo Danjou' my $newval = $record->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new record value (with all fields) my $hashref2 = $record->param; # same as $record->content; =head1 METHODS =head2 param sets and gets content value. =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Row> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Role/Base.pm b/lib/Net/Google/Spreadsheets/Role/Base.pm deleted file mode 100644 index 0c710cd..0000000 --- a/lib/Net/Google/Spreadsheets/Role/Base.pm +++ /dev/null @@ -1,127 +0,0 @@ -package Net::Google::Spreadsheets::Role::Base; -use Moose::Role; -use namespace::clean -except => 'meta'; -use Carp; - -has service => ( - isa => 'Net::Google::Spreadsheets', - is => 'ro', - required => 1, - lazy_build => 1, - weak_ref => 1, -); - -sub _build_service { shift->container->service }; - -my %ns = ( - gd => 'http://schemas.google.com/g/2005', - gs => 'http://schemas.google.com/spreadsheets/2006', - gsx => 'http://schemas.google.com/spreadsheets/2006/extended', - batch => 'http://schemas.google.com/gdata/batch', -); - -while (my ($prefix, $uri) = each %ns) { - __PACKAGE__->meta->add_method( - "${prefix}ns" => sub { - XML::Atom::Namespace->new($prefix, $uri) - } - ); -} - -my %rel2label = ( - edit => 'editurl', - self => 'selfurl', -); - -for (values %rel2label) { - has $_ => (isa => 'Str', is => 'ro'); -} - -has atom => ( - isa => 'XML::Atom::Entry', - is => 'rw', - trigger => sub { - my ($self, $arg) = @_; - my $id = $self->atom->get($self->ns, 'id'); - croak "can't set different id!" if $self->id && $self->id ne $id; - $self->from_atom; - }, - handles => ['ns', 'elem', 'author'], -); - -has id => ( - isa => 'Str', - is => 'ro', -); - -has title => ( - isa => 'Str', - is => 'rw', - default => 'untitled', - trigger => sub {$_[0]->update} -); - -has etag => ( - isa => 'Str', - is => 'rw', -); - -has container => ( - isa => 'Maybe[Net::Google::Spreadsheets::Role::Base]', - is => 'ro', -); - -sub from_atom { - my ($self) = @_; - $self->{title} = $self->atom->title; - $self->{id} = $self->atom->get($self->ns, 'id'); - $self->etag($self->elem->getAttributeNS($self->gdns->{uri}, 'etag')); - for ($self->atom->link) { - my $label = $rel2label{$_->rel} or next; - $self->{$label} = $_->href; - } -} - -sub to_atom { - my ($self) = @_; - $XML::Atom::DefaultVersion = 1; - my $entry = XML::Atom::Entry->new; - $entry->title($self->title) if $self->title; - return $entry; -} - -sub sync { - my ($self) = @_; - my $entry = $self->service->entry($self->selfurl); - $self->atom($entry); -} - -sub update { - my ($self) = @_; - $self->etag or return; - my $atom = $self->service->put( - { - self => $self, - entry => $self->to_atom, - } - ); - $self->container->sync; - $self->atom($atom); -} - -sub delete { - my $self = shift; - my $res = $self->service->request( - { - uri => $self->editurl, - method => 'DELETE', - header => {'If-Match' => $self->etag}, - } - ); - $self->container->sync if $res->is_success; - return $res->is_success; -} - -1; - -__END__ diff --git a/lib/Net/Google/Spreadsheets/Role/HasContent.pm b/lib/Net/Google/Spreadsheets/Role/HasContent.pm deleted file mode 100644 index 9b04bee..0000000 --- a/lib/Net/Google/Spreadsheets/Role/HasContent.pm +++ /dev/null @@ -1,27 +0,0 @@ -package Net::Google::Spreadsheets::Role::HasContent; -use Moose::Role; -use namespace::clean -except => 'meta'; - -has content => ( - isa => 'HashRef', - is => 'rw', - default => sub { +{} }, - trigger => sub { $_[0]->update }, -); - -sub param { - my ($self, $arg) = @_; - return $self->content unless $arg; - if (ref $arg && (ref $arg eq 'HASH')) { - return $self->content( - { - %{$self->content}, - %$arg, - } - ); - } else { - return $self->content->{$arg}; - } -} - -1; diff --git a/lib/Net/Google/Spreadsheets/Role/Service.pm b/lib/Net/Google/Spreadsheets/Role/Service.pm deleted file mode 100644 index 55c9cfc..0000000 --- a/lib/Net/Google/Spreadsheets/Role/Service.pm +++ /dev/null @@ -1,50 +0,0 @@ -package Net::Google::Spreadsheets::Role::Service; -use Moose::Role; - -use Carp; -use Net::Google::AuthSub; -use Net::Google::Spreadsheets::UserAgent; - -has source => ( - isa => 'Str', - is => 'ro', - required => 1, - lazy_build => 1, -); - -has username => ( isa => 'Str', is => 'ro', required => 1 ); -has password => ( isa => 'Str', is => 'ro', required => 1 ); - -has ua => ( - isa => 'Net::Google::Spreadsheets::UserAgent', - is => 'ro', - handles => [qw(request feed entry post put)], - required => 1, - lazy_build => 1, -); - -sub _build_ua { - my $self = shift; - my $authsub = Net::Google::AuthSub->new( - service => 'wise', - source => $self->source, - ); - my $res = $authsub->login( - $self->username, - $self->password, - ); - unless ($res && $res->is_success) { - croak 'Net::Google::AuthSub login failed'; - } - return Net::Google::Spreadsheets::UserAgent->new( - source => $self->source, - auth => $res->auth, - ); -} - -sub BUILD { - my ($self) = @_; - $self->ua; #check if login ok? -} - -1; diff --git a/lib/Net/Google/Spreadsheets/Row.pm b/lib/Net/Google/Spreadsheets/Row.pm index 3f28259..98dfb90 100644 --- a/lib/Net/Google/Spreadsheets/Row.pm +++ b/lib/Net/Google/Spreadsheets/Row.pm @@ -1,169 +1,155 @@ package Net::Google::Spreadsheets::Row; use Moose; use namespace::clean -except => 'meta'; +use Net::Google::GData; use XML::Atom::Util qw(nodelist); with - 'Net::Google::Spreadsheets::Role::Base', - 'Net::Google::Spreadsheets::Role::HasContent'; + 'Net::Google::GData::Role::Entry', + 'Net::Google::GData::Role::HasContent'; after from_atom => sub { my ($self) = @_; - for my $node (nodelist($self->elem, $self->gsxns->{uri}, '*')) { + for my $node (nodelist($self->elem, $self->service->ns('gsx')->{uri}, '*')) { $self->{content}->{$node->localname} = $node->textContent; } }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->{content}}) { - $entry->set($self->gsxns, $key, $value); + $entry->set($self->service->ns('gsx'), $key, $value); } return $entry; }; __PACKAGE__->meta->make_immutable; -sub param { - my ($self, $arg) = @_; - return $self->content unless $arg; - if (ref $arg && (ref $arg eq 'HASH')) { - return $self->content( - { - %{$self->content}, - %$arg, - } - ); - } else { - return $self->content->{$arg}; - } -} - 1; __END__ =head1 NAME Net::Google::Spreadsheets::Row - A representation class for Google Spreadsheet row. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a row my $row = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->row( { sq => 'id = 1000' } ); # get the content of a row my $hashref = $row->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $row->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $row->param('name'); # returns 'Nobuo Danjou' my $newval = $row->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new row value (with all fields) my $hashref2 = $row->param; # same as $row->content; =head1 METHODS =head2 param sets and gets content value. =head1 CAVEATS Space characters in hash key of rows will be removed when you access rows. See below. my $ws = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'})->worksheet(1); $ws->batchupdate_cell( {col => 1,row => 1, input_value => 'name'}, {col => 2,row => 1, input_value => 'mail address'}, ); $ws->add_row( { name => 'my name', mailaddress => '[email protected]', # above passes, below fails. # 'mail address' => '[email protected]', } ); Instead, Net::Google::Spreadsheets::Table and Net::Google::Spreadsheets::Record allows space characters in column name. my $s = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'}); my $t = $s->add_table( { worksheet => $s->worksheet(1), columns => ['name', 'mail address'], } ); $t->add_record( { name => 'my name', 'mail address' => '[email protected]', } ); =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Table.pm b/lib/Net/Google/Spreadsheets/Table.pm index b2c8583..fb1da19 100644 --- a/lib/Net/Google/Spreadsheets/Table.pm +++ b/lib/Net/Google/Spreadsheets/Table.pm @@ -1,233 +1,228 @@ package Net::Google::Spreadsheets::Table; use Moose; use Moose::Util::TypeConstraints; use namespace::clean -except => 'meta'; +use Net::Google::GData; use XML::Atom::Util qw(nodelist first create_element); -with 'Net::Google::Spreadsheets::Role::Base'; +with 'Net::Google::GData::Role::Entry'; subtype 'ColumnList' => as 'ArrayRef[Net::Google::Spreadsheets::Table::Column]'; coerce 'ColumnList' => from 'ArrayRef[HashRef]' => via { [ map {Net::Google::Spreadsheets::Table::Column->new($_)} @$_ ] }; coerce 'ColumnList' => from 'ArrayRef[Str]' => via { my @c; my $index = 0; for my $value (@$_) { push @c, Net::Google::Spreadsheets::Table::Column->new( index => ++$index, name => $value, ); } \@c; }; coerce 'ColumnList' => from 'HashRef' => via { my @c; while (my ($key, $value) = each(%$_)) { push @c, Net::Google::Spreadsheets::Table::Column->new( index => $key, name => $value, ); } \@c; }; subtype 'WorksheetName' => as 'Str'; coerce 'WorksheetName' => from 'Net::Google::Spreadsheets::Worksheet' => via { $_->title }; - -has record_feed => ( - traits => ['Net::Google::Spreadsheets::Traits::Feed'], - is => 'ro', - isa => 'Str', +feedurl record => ( entry_class => 'Net::Google::Spreadsheets::Record', - entry_arg_builder => sub { + arg_builder => sub { my ($self, $args) = @_; return {content => $args}; }, - from_atom => sub { - my $self = shift; - $self->{record_feed} = first($self->elem, '', 'content')->getAttribute('src'); - }, + as_content_src => 1, ); has summary => ( is => 'rw', isa => 'Str' ); has worksheet => ( is => 'ro', isa => 'WorksheetName', coerce => 1 ); has header => ( is => 'ro', isa => 'Int', required => 1, default => 1 ); has start_row => ( is => 'ro', isa => 'Int', required => 1, default => 2 ); has num_rows => ( is => 'ro', isa => 'Int' ); has columns => ( is => 'ro', isa => 'ColumnList', coerce => 1 ); has insertion_mode => ( is => 'ro', isa => (enum ['insert', 'overwrite']), default => 'overwrite' ); after from_atom => sub { my ($self) = @_; - my $gsns = $self->gsns->{uri}; + my $gsns = $self->service->ns('gs')->{uri}; my $elem = $self->elem; $self->{summary} = $self->atom->summary; $self->{worksheet} = first( $elem, $gsns, 'worksheet')->getAttribute('name'); $self->{header} = first( $elem, $gsns, 'header')->getAttribute('row'); my @columns; my $data = first($elem, $gsns, 'data'); $self->{insertion_mode} = $data->getAttribute('insertionMode'); $self->{start_row} = $data->getAttribute('startRow'); $self->{num_rows} = $data->getAttribute('numRows'); for (nodelist($data, $gsns, 'column')) { push @columns, Net::Google::Spreadsheets::Table::Column->new( index => $_->getAttribute('index'), name => $_->getAttribute('name'), ); } $self->{columns} = \@columns; }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); + my $gsns = $self->service->ns('gs')->{uri}; $entry->summary($self->summary) if $self->summary; - $entry->set($self->gsns, 'worksheet', '', {name => $self->worksheet}); - $entry->set($self->gsns, 'header', '', {row => $self->header}); - my $data = create_element($self->gsns, 'data'); + $entry->set($gsns, 'worksheet', '', {name => $self->worksheet}); + $entry->set($gsns, 'header', '', {row => $self->header}); + my $data = create_element($gsns, 'data'); $data->setAttribute(startRow => $self->start_row); $data->setAttribute(insertionMode => $self->insertion_mode); $data->setAttribute(startRow => $self->start_row) if $self->start_row; for ( @{$self->columns} ) { - my $column = create_element($self->gsns, 'column'); + my $column = create_element($gsns, 'column'); $column->setAttribute(index => $_->index); $column->setAttribute(name => $_->name); $data->appendChild($column); } - $entry->set($self->gsns, 'data', $data); + $entry->set($gsns, 'data', $data); return $entry; }; __PACKAGE__->meta->make_immutable; package # hide from PAUSE Net::Google::Spreadsheets::Table::Column; use Moose; has 'index' => ( is => 'ro', isa => 'Str' ); has 'name' => ( is => 'ro', isa => 'Str' ); __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Table - A representation class for Google Spreadsheet table. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a table my $table = $service->spreadsheet( { title => 'list for new year cards', } )->table( { title => 'sample table', } ); # create a record my $r = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # get records my @records = $table->records; # search records @records = $table->records({sq => 'age > 20'}); # search a record my $record = $table->record({sq => 'name = "Nobuo Danjou"'}); =head1 METHODS =head2 records(\%condition) Returns a list of Net::Google::Spreadsheets::Record objects. Acceptable arguments are: =over 4 =item sq Structured query on the full text in the worksheet. see the URL below for detail. =item orderby Set column name to use for ordering. =item reverse Set 'true' or 'false'. The default is 'false'. =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#RecordParameters> for details. =head2 record(\%condition) Returns first item of records(\%condition) if available. =head2 add_record(\%contents) Creates new record and returns a Net::Google::Spreadsheets::Record object representing it. Arguments are contents of a row as a hashref. my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Record> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Traits/Feed.pm b/lib/Net/Google/Spreadsheets/Traits/Feed.pm deleted file mode 100644 index ea015ff..0000000 --- a/lib/Net/Google/Spreadsheets/Traits/Feed.pm +++ /dev/null @@ -1,101 +0,0 @@ -package Net::Google::Spreadsheets::Traits::Feed; -use Moose::Role; - -has entry_class => ( - is => 'ro', - isa => 'Str', - required => 1, -); - -has entry_arg_builder => ( - is => 'ro', - isa => 'CodeRef', - required => 1, - default => sub { - return sub { - my ($self, $args) = @_; - return $args || {}; - }; - }, -); - -has query_arg_builder => ( - is => 'ro', - isa => 'CodeRef', - required => 1, - default => sub { - return sub { - my ($self, $args) = @_; - return $args || {}; - }; - }, -); - -has from_atom => ( - is => 'ro', - isa => 'CodeRef', - required => 1, - default => sub { - return sub {}; - } -); - -after install_accessors => sub { - my $attr = shift; - my $class = $attr->associated_class; - my $key = $attr->name; - - my $entry_class = $attr->entry_class; - my $arg_builder = $attr->entry_arg_builder; - my $query_builder = $attr->query_arg_builder; - my $from_atom = $attr->from_atom; - my $method_base = lc [ split('::', $entry_class) ]->[-1]; - - $class->add_method( - "add_${method_base}" => sub { - my ($self, $args) = @_; - Class::MOP::load_class($entry_class); - $args = $arg_builder->($self, $args); - my $entry = $entry_class->new($args)->to_atom; - my $atom = $self->service->post($self->$key, $entry); - $self->sync; - return $entry_class->new( - container => $self, - atom => $atom, - ); - } - ); - - $class->add_method( - "${method_base}s" => sub { - my ($self, $cond) = @_; - $self->$key or return; - Class::MOP::load_class($entry_class); - $cond = $query_builder->($self, $cond); - my $feed = $self->service->feed($self->$key, $cond); - return map { - $entry_class->new( - container => $self, - atom => $_, - ) - } $feed->entries; - } - ); - - $class->add_method( - $method_base => sub { - my ($self, $cond) = @_; - my $method = "${method_base}s"; - return [ $self->$method($cond) ]->[0]; - } - ); - - $class->add_after_method_modifier( - 'from_atom' => sub { - my $self = shift; - $from_atom->($self); - } - ); -}; - -1; diff --git a/lib/Net/Google/Spreadsheets/UserAgent.pm b/lib/Net/Google/Spreadsheets/UserAgent.pm deleted file mode 100644 index ac2fab2..0000000 --- a/lib/Net/Google/Spreadsheets/UserAgent.pm +++ /dev/null @@ -1,154 +0,0 @@ -package Net::Google::Spreadsheets::UserAgent; -use Moose; -use namespace::clean -except => 'meta'; -use Carp; -use LWP::UserAgent; -use URI; -use XML::Atom::Entry; -use XML::Atom::Feed; - -has source => ( - isa => 'Str', - is => 'ro', - required => 1, -); - -has auth => ( - isa => 'Str', - is => 'rw', - required => 1, -); - -has ua => ( - isa => 'LWP::UserAgent', - is => 'ro', - required => 1, - lazy_build => 1, -); -sub _build_ua { - my $self = shift; - my $ua = LWP::UserAgent->new( - agent => $self->source, - requests_redirectable => [], - ); - $ua->default_headers( - HTTP::Headers->new( - Authorization => sprintf('GoogleLogin auth=%s', $self->auth), - GData_Version => '3.0', - ) - ); - return $ua; -} - -__PACKAGE__->meta->make_immutable; - -sub request { - my ($self, $args) = @_; - my $method = delete $args->{method}; - $method ||= $args->{content} ? 'POST' : 'GET'; - my $uri = URI->new($args->{'uri'}); - $uri->query_form($args->{query}) if $args->{query}; - my $req = HTTP::Request->new($method => "$uri"); - $req->content($args->{content}) if $args->{content}; - $req->header('Content-Type' => $args->{content_type}) if $args->{content_type}; - if ($args->{header}) { - while (my @pair = each %{$args->{header}}) { - $req->header(@pair); - } - } - my $res = eval {$self->ua->request($req)}; - if ($ENV{DEBUG}) { - warn $res->request->as_string; - warn $res->as_string; - } - if ($@ || !$res->is_success) { - die sprintf( - "request for '%s' failed:\n\t%s\n\t%s\n\t", - $uri, - $@ || $res->status_line, - $! || $res->content - ); - } - my $type = $res->content_type; - if ($res->content_length && $type !~ m{^application/atom\+xml}) { - die sprintf("Content-Type of response for '%s' is not 'application/atom+xml': %s", $uri, $type); - } - if (my $res_obj = $args->{response_object}) { - my $obj = eval {$res_obj->new(\($res->content))}; - croak sprintf("response for '%s' is broken: %s", $uri, $@) if $@; - return $obj; - } - return $res; -} - -sub feed { - my ($self, $url, $query) = @_; - return $self->request( - { - uri => $url, - query => $query || undef, - response_object => 'XML::Atom::Feed', - } - ); -} - -sub entry { - my ($self, $url, $query) = @_; - return $self->request( - { - uri => $url, - query => $query || undef, - response_object => 'XML::Atom::Entry', - } - ); -} - -sub post { - my ($self, $url, $entry, $header) = @_; - return $self->request( - { - uri => $url, - content => $entry->as_xml, - header => $header || undef, - content_type => 'application/atom+xml', - response_object => ref $entry, - } - ); -} - -sub put { - my ($self, $args) = @_; - return $self->request( - { - method => 'PUT', - uri => $args->{self}->editurl, - content => $args->{entry}->as_xml, - header => {'If-Match' => $args->{self}->etag }, - content_type => 'application/atom+xml', - response_object => 'XML::Atom::Entry', - } - ); -} - -1; -__END__ - -=head1 NAME - -Net::Google::Spreadsheets::UserAgent - UserAgent for Net::Google::Spreadsheets. - -=head1 SEE ALSO - -L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> - -L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> - -L<Net::Google::AuthSub> - -L<Net::Google::Spreadsheets> - -=head1 AUTHOR - -Nobuo Danjou E<lt>[email protected]<gt> - -=cut diff --git a/lib/Net/Google/Spreadsheets/Worksheet.pm b/lib/Net/Google/Spreadsheets/Worksheet.pm index e9366f6..a556bfd 100644 --- a/lib/Net/Google/Spreadsheets/Worksheet.pm +++ b/lib/Net/Google/Spreadsheets/Worksheet.pm @@ -1,258 +1,259 @@ package Net::Google::Spreadsheets::Worksheet; use Moose; use namespace::clean -except => 'meta'; use Net::Google::GData; with 'Net::Google::GData::Role::Entry'; use Carp; use Net::Google::Spreadsheets::Cell; use XML::Atom::Util qw(first); feedurl row => ( entry_class => 'Net::Google::Spreadsheets::Row', as_content_src => 1, arg_builder => sub { my ($self, $args) = @_; return {content => $args}; }, ); feedurl cell => ( entry_class => 'Net::Google::Spreadsheets::Cell', can_add => 0, rel => 'http://schemas.google.com/spreadsheets/2006#cellsfeed', query_builder => sub { my ($self, $args) = @_; if (my $col = delete $args->{col}) { $args->{'max-col'} = $col; $args->{'min-col'} = $col; $args->{'return-empty'} = 'true'; } if (my $row = delete $args->{row}) { $args->{'max-row'} = $row; $args->{'min-row'} = $row; $args->{'return-empty'} = 'true'; } return $args; }, ); has row_count => ( isa => 'Int', is => 'rw', default => 100, trigger => sub {$_[0]->update} ); has col_count => ( isa => 'Int', is => 'rw', default => 20, trigger => sub {$_[0]->update} ); around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->service->ns('gs'), 'rowCount', $self->row_count); $entry->set($self->service->ns('gs'), 'colCount', $self->col_count); return $entry; }; after from_atom => sub { my ($self) = @_; $self->{row_count} = $self->atom->get($self->service->ns('gs'), 'rowCount'); $self->{col_count} = $self->atom->get($self->service->ns('gs'), 'colCount'); }; __PACKAGE__->meta->make_immutable; sub batchupdate_cell { my ($self, @args) = @_; my $feed = XML::Atom::Feed->new; for ( @args ) { - my $id = sprintf("%s/R%sC%s",$self->cellsfeed, $_->{row}, $_->{col}); + my $id = sprintf("%s/R%sC%s",$self->cell_feedurl, $_->{row}, $_->{col}); $_->{id} = $_->{editurl} = $id; + $_->{container} = $self, my $entry = Net::Google::Spreadsheets::Cell->new($_)->to_atom; $entry->set($self->service->ns('batch'), operation => '', {type => 'update'}); $entry->set($self->service->ns('batch'), id => $id); $feed->add_entry($entry); } my $res_feed = $self->service->post( - $self->cellsfeed."/batch", + $self->cell_feedurl."/batch", $feed, {'If-Match' => '*'} ); $self->sync; return map { Net::Google::Spreadsheets::Cell->new( atom => $_, container => $self, ) } grep { my $node = first( $_->elem, $self->service->ns('batch')->{uri}, 'status' ); $node->getAttribute('code') == 200; } $res_feed->entries; } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Worksheet - Representation of worksheet. =head1 SYNOPSIS my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); my $ss = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); my $worksheet = $ss->worksheet({title => 'Sheet1'}); # update cell by batch request $worksheet->batchupdate_cell( {col => 1, row => 1, input_value => 'name'}, {col => 2, row => 1, input_value => 'nick'}, {col => 3, row => 1, input_value => 'mail'}, {col => 4, row => 1, input_value => 'age'}, ); # get a cell object my $cell = $worksheet->cell({col => 1, row => 1}); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # get rows my @rows = $worksheet->rows; # search rows @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); =head1 METHODS =head2 rows(\%condition) Returns a list of Net::Google::Spreadsheets::Row objects. Acceptable arguments are: =over 4 =item sq Structured query on the full text in the worksheet. see the URL below for detail. =item orderby Set column name to use for ordering. =item reverse Set 'true' or 'false'. The default is 'false'. =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#ListParameters> for details. =head2 row(\%condition) Returns first item of rows(\%condition) if available. =head2 add_row(\%contents) Creates new row and returns a Net::Google::Spreadsheets::Row object representing it. Arguments are contents of a row as a hashref. my $row = $ws->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); =head2 cells(\%args) Returns a list of Net::Google::Spreadsheets::Cell objects. Acceptable arguments are: =over 4 =item min-row =item max-row =item min-col =item max-col =item range =item return-empty =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#CellParameters> for details. =head2 cell(\%args) Returns Net::Google::Spreadsheets::Cell object. Arguments are: =over 4 =item col =item row =back =head2 batchupdate_cell(@args) update multiple cells with a batch request. Pass a list of hash references containing: =over 4 =item col =item row =item input_value =back =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/t/08_error.t b/t/08_error.t index c92bf79..6459e7c 100644 --- a/t/08_error.t +++ b/t/08_error.t @@ -1,78 +1,78 @@ use strict; use Test::More; use Test::Exception; use Test::MockModule; use Test::MockObject; use LWP::UserAgent; use Net::Google::Spreadsheets; throws_ok { my $service = Net::Google::Spreadsheets->new( username => 'foo', password => 'bar', ); } qr{Net::Google::AuthSub login failed}; { my $res = Test::MockObject->new; $res->mock(is_success => sub {return 1}); $res->mock(auth => sub {return 'foobar'}); my $auth = Test::MockModule->new('Net::Google::AuthSub'); $auth->mock('login' => sub {return $res}); ok my $service = Net::Google::Spreadsheets->new( username => 'foo', password => 'bar', ); - is $service->ua->auth, 'foobar'; + is $service->ua->default_headers->header('Authorization'), 'GoogleLogin auth=foobar'; my $ua = Test::MockModule->new('LWP::UserAgent'); { $ua->mock('request' => sub {return HTTP::Response->parse(<<'END')}); 302 Found Location: http://www.google.com/ END throws_ok { $service->spreadsheets; } qr{302 Found}; } { $ua->mock('request' => sub {return HTTP::Response->parse(<<END)}); 200 OK Content-Type: application/atom+xml Content-Length: 1 1 END throws_ok { $service->spreadsheets; } qr{broken}; } { $ua->mock('request' => sub {return HTTP::Response->parse(<<END)}); 200 OK Content-Type: text/html Content-Length: 13 <html></html> END throws_ok { $service->spreadsheets; } qr{is not 'application/atom\+xml'}; } { $ua->mock('request' => sub {return HTTP::Response->parse(<<'END')}); 200 OK ETag: W/"hogehoge" Content-Type: application/atom+xml; charset=UTF-8; type=feed Content-Length: 958 <?xml version='1.0' encoding='UTF-8'?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearch/1.1/' xmlns:gd='http://schemas.google.com/g/2005' gd:etag='W/&quot;hogehoge&quot;'><id>http://spreadsheets.google.com/feeds/spreadsheets/private/full</id><updated>2009-08-15T09:41:23.289Z</updated><category scheme='http://schemas.google.com/spreadsheets/2006' term='http://schemas.google.com/spreadsheets/2006#spreadsheet'/><title>Available Spreadsheets - [email protected]</title><link rel='alternate' type='text/html' href='http://docs.google.com'/><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://spreadsheets.google.com/feeds/spreadsheets/private/full'/><link rel='self' type='application/atom+xml' href='http://spreadsheets.google.com/feeds/spreadsheets/private/full?tfe='/><openSearch:totalResults>0</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex></feed> END my @ss = $service->spreadsheets; is scalar @ss, 0; } } done_testing;
lopnor/Net-Google-Spreadsheets
7953a8ac11f8ed1dfb3c8cda3575f1c66141ddb0
spreadsheet and worksheet moved to gdata
diff --git a/Makefile.PL b/Makefile.PL index b2037c3..db0ad95 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,24 +1,25 @@ use inc::Module::Install; name 'Net-Google-Spreadsheets'; all_from 'lib/Net/Google/Spreadsheets.pm'; requires 'Carp'; requires 'XML::Atom'; requires 'Net::Google::AuthSub'; requires 'Crypt::SSLeay'; requires 'LWP::UserAgent'; requires 'URI'; requires 'Moose' => 0.34; +requires 'MooseX::Role::Parameterized'; requires 'Path::Class'; tests 't/*.t'; author_tests 'xt'; build_requires 'Test::More' => '0.88'; build_requires 'Test::Exception'; build_requires 'Test::MockModule'; build_requires 'Test::MockObject'; use_test_base; auto_include; auto_set_repository; WriteAll; diff --git a/lib/Net/Google/Spreadsheets/Spreadsheet.pm b/lib/Net/Google/Spreadsheets/Spreadsheet.pm index ca28354..e141475 100644 --- a/lib/Net/Google/Spreadsheets/Spreadsheet.pm +++ b/lib/Net/Google/Spreadsheets/Spreadsheet.pm @@ -1,231 +1,231 @@ package Net::Google::Spreadsheets::Spreadsheet; use Moose; use namespace::clean -except => 'meta'; use Net::Google::GData; with 'Net::Google::GData::Role::Entry'; use Path::Class; use URI; has +title => ( is => 'ro', ); has key => ( isa => 'Str', is => 'ro', ); feedurl worksheet => ( entry_class => 'Net::Google::Spreadsheets::Worksheet', as_content_src => 1, ); feedurl table => ( entry_class => 'Net::Google::Spreadsheets::Table', - rel => 'http://schemas.google.com/spreadsheets/2006#tablefeed', + rel => 'http://schemas.google.com/spreadsheets/2006#tablesfeed', ); after from_atom => sub { my ($self) = @_; $self->{key} = file(URI->new($self->id)->path)->basename; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Spreadsheet - Representation of spreadsheet. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # create a worksheet my $worksheet = $spreadsheet->add_worksheet( { title => 'foobar', col_count => 10, row_count => 100, } ); # list worksheets my @ws = $spreadsheet->worksheets; # find a worksheet my $ws = $spreadsheet->worksheet({title => 'fooba'}); # create a table my $table = $spreadsheet->add_table( { title => 'sample table', worksheet => $worksheet, columns => ['id', 'username', 'mail', 'password'], } ); # list tables my @t = $spreadsheet->tables; # find a worksheet my $t = $spreadsheet->table({title => 'sample table'}); =head1 METHODS =head2 worksheets(\%condition) Returns a list of Net::Google::Spreadsheets::Worksheet objects. Acceptable arguments are: =over 4 =item title =item title-exact =back =head2 worksheet(\%condition) Returns first item of worksheets(\%condition) if available. =head2 add_worksheet(\%attribuets) Creates new worksheet and returns a Net::Google::Spreadsheets::Worksheet object representing it. Arguments (all optional) are: =over 4 =item title =item col_count =item row_count =back =head2 tables(\%condition) Returns a list of Net::Google::Spreadsheets::Table objects. Acceptable arguments are: =over 4 =item title =item title-exact =back =head2 table(\%condition) Returns first item of tables(\%condition) if available. =head2 add_table(\%attribuets) Creates new table and returns a Net::Google::Spreadsheets::Table object representing it. Arguments are: =over 4 =item title (optional) =item summary (optional) =item worksheet Worksheet where the table lives. worksheet instance or the title. =item header (optional, default = 1) Row number of header =item start_row (optional, default = 2) The index of the first row of the data section. =item insertion_mode (optional, default = 'overwrite') Insertion mode. 'insert' inserts new row into the worksheet when creating record, 'overwrite' tries to use existing rows in the worksheet. =item columns Columns of the table. you can specify them as hashref, arrayref, arrayref of hashref. $ss->add_table( { worksheet => $ws, columns => [ {index => 1, name => 'foo'}, {index => 2, name => 'bar'}, {index => 3, name => 'baz'}, ], } ); $ss->add_table( { worksheet => $ws, columns => { A => 'foo', B => 'bar', C => 'baz', } } ); $ss->add_table( { worksheet => $ws, columns => ['foo', 'bar', 'baz'], } ); 'index' of the first case and hash key of the second case is column index of the worksheet. In the third case, the columns is automatically placed to the columns of the worksheet from 'A' to 'Z' order. =back =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Table> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Worksheet.pm b/lib/Net/Google/Spreadsheets/Worksheet.pm index dcbc5e5..e9366f6 100644 --- a/lib/Net/Google/Spreadsheets/Worksheet.pm +++ b/lib/Net/Google/Spreadsheets/Worksheet.pm @@ -1,269 +1,258 @@ package Net::Google::Spreadsheets::Worksheet; use Moose; -use Carp; use namespace::clean -except => 'meta'; +use Net::Google::GData; -with 'Net::Google::Spreadsheets::Role::Base'; +with 'Net::Google::GData::Role::Entry'; +use Carp; use Net::Google::Spreadsheets::Cell; use XML::Atom::Util qw(first); -has row_feed => ( - traits => ['Net::Google::Spreadsheets::Traits::Feed'], - is => 'ro', - isa => 'Str', +feedurl row => ( entry_class => 'Net::Google::Spreadsheets::Row', - entry_arg_builder => sub { + as_content_src => 1, + arg_builder => sub { my ($self, $args) = @_; return {content => $args}; }, - from_atom => sub { - my $self = shift; - $self->{row_feed} = $self->atom->content->elem->getAttribute('src'); - }, ); -has cellsfeed => ( - traits => ['Net::Google::Spreadsheets::Traits::Feed'], - is => 'ro', - isa => 'Str', +feedurl cell => ( entry_class => 'Net::Google::Spreadsheets::Cell', - entry_arg_builder => sub { - my ($self, $args) = @_; - croak 'you can\'t call add_cell!'; - }, - query_arg_builder => sub { + can_add => 0, + rel => 'http://schemas.google.com/spreadsheets/2006#cellsfeed', + query_builder => sub { my ($self, $args) = @_; if (my $col = delete $args->{col}) { $args->{'max-col'} = $col; $args->{'min-col'} = $col; $args->{'return-empty'} = 'true'; } if (my $row = delete $args->{row}) { $args->{'max-row'} = $row; $args->{'min-row'} = $row; $args->{'return-empty'} = 'true'; } return $args; }, - from_atom => sub { - my ($self) = @_; - ($self->{cellsfeed}) = map {$_->href} grep { - $_->rel eq 'http://schemas.google.com/spreadsheets/2006#cellsfeed' - } $self->atom->link; - } + ); has row_count => ( isa => 'Int', is => 'rw', default => 100, trigger => sub {$_[0]->update} ); has col_count => ( isa => 'Int', is => 'rw', default => 20, trigger => sub {$_[0]->update} ); around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); - $entry->set($self->gsns, 'rowCount', $self->row_count); - $entry->set($self->gsns, 'colCount', $self->col_count); + $entry->set($self->service->ns('gs'), 'rowCount', $self->row_count); + $entry->set($self->service->ns('gs'), 'colCount', $self->col_count); return $entry; }; after from_atom => sub { my ($self) = @_; - $self->{row_count} = $self->atom->get($self->gsns, 'rowCount'); - $self->{col_count} = $self->atom->get($self->gsns, 'colCount'); + $self->{row_count} = $self->atom->get($self->service->ns('gs'), 'rowCount'); + $self->{col_count} = $self->atom->get($self->service->ns('gs'), 'colCount'); }; __PACKAGE__->meta->make_immutable; sub batchupdate_cell { my ($self, @args) = @_; my $feed = XML::Atom::Feed->new; for ( @args ) { my $id = sprintf("%s/R%sC%s",$self->cellsfeed, $_->{row}, $_->{col}); $_->{id} = $_->{editurl} = $id; my $entry = Net::Google::Spreadsheets::Cell->new($_)->to_atom; - $entry->set($self->batchns, operation => '', {type => 'update'}); - $entry->set($self->batchns, id => $id); + $entry->set($self->service->ns('batch'), operation => '', {type => 'update'}); + $entry->set($self->service->ns('batch'), id => $id); $feed->add_entry($entry); } - my $res_feed = $self->service->post($self->cellsfeed."/batch", $feed, {'If-Match' => '*'}); + my $res_feed = $self->service->post( + $self->cellsfeed."/batch", + $feed, + {'If-Match' => '*'} + ); $self->sync; return map { Net::Google::Spreadsheets::Cell->new( atom => $_, container => $self, ) } grep { my $node = first( - $_->elem, $self->batchns->{uri}, 'status' + $_->elem, $self->service->ns('batch')->{uri}, 'status' ); $node->getAttribute('code') == 200; } $res_feed->entries; } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Worksheet - Representation of worksheet. =head1 SYNOPSIS my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); my $ss = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); my $worksheet = $ss->worksheet({title => 'Sheet1'}); # update cell by batch request $worksheet->batchupdate_cell( {col => 1, row => 1, input_value => 'name'}, {col => 2, row => 1, input_value => 'nick'}, {col => 3, row => 1, input_value => 'mail'}, {col => 4, row => 1, input_value => 'age'}, ); # get a cell object my $cell = $worksheet->cell({col => 1, row => 1}); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # get rows my @rows = $worksheet->rows; # search rows @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); =head1 METHODS =head2 rows(\%condition) Returns a list of Net::Google::Spreadsheets::Row objects. Acceptable arguments are: =over 4 =item sq Structured query on the full text in the worksheet. see the URL below for detail. =item orderby Set column name to use for ordering. =item reverse Set 'true' or 'false'. The default is 'false'. =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#ListParameters> for details. =head2 row(\%condition) Returns first item of rows(\%condition) if available. =head2 add_row(\%contents) Creates new row and returns a Net::Google::Spreadsheets::Row object representing it. Arguments are contents of a row as a hashref. my $row = $ws->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); =head2 cells(\%args) Returns a list of Net::Google::Spreadsheets::Cell objects. Acceptable arguments are: =over 4 =item min-row =item max-row =item min-col =item max-col =item range =item return-empty =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#CellParameters> for details. =head2 cell(\%args) Returns Net::Google::Spreadsheets::Cell object. Arguments are: =over 4 =item col =item row =back =head2 batchupdate_cell(@args) update multiple cells with a batch request. Pass a list of hash references containing: =over 4 =item col =item row =item input_value =back =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/t/03_worksheet.t b/t/03_worksheet.t index 3ff3ca8..49d8eec 100644 --- a/t/03_worksheet.t +++ b/t/03_worksheet.t @@ -1,69 +1,69 @@ use t::Util; use Test::More; ok my $spreadsheet = spreadsheet, 'getting spreadsheet'; { ok my @ws = $spreadsheet->worksheets, 'getting worksheet'; ok scalar @ws; isa_ok($ws[0], 'Net::Google::Spreadsheets::Worksheet'); } my $args = { - title => 'new worksheet', + title => 'new worksheet '. scalar localtime, row_count => 10, col_count => 3, }; { my $before = scalar $spreadsheet->worksheets; ok my $ws = $spreadsheet->add_worksheet($args), "adding worksheet named '$args->{title}'"; isa_ok $ws, 'Net::Google::Spreadsheets::Worksheet'; is $ws->title, $args->{title}, 'title is correct'; is $ws->row_count, $args->{row_count}, 'row_count is correct'; is $ws->col_count, $args->{col_count}, 'col_count is correct'; my @ws = $spreadsheet->worksheets; is scalar @ws, $before + 1; ok grep {$_->title eq $args->{title} } @ws; } { my $ws = $spreadsheet->worksheet({title => $args->{title}}); isa_ok $ws, 'Net::Google::Spreadsheets::Worksheet'; is $ws->title, $args->{title}; is $ws->row_count, $args->{row_count}; is $ws->col_count, $args->{col_count}; - $args->{title} = "title changed"; + $args->{title} = "title changed " .scalar localtime; ok $ws->title($args->{title}), "changing title to $args->{title}"; is $ws->title, $args->{title}; is $ws->atom->title, $args->{title}; for (1 .. 2) { my $col_count = $ws->col_count + 1; my $row_count = $ws->row_count + 1; is $ws->col_count($col_count), $col_count, "changing col_count to $col_count"; - is $ws->atom->get($ws->gsns, 'colCount'), $col_count; + is $ws->atom->get($ws->service->ns('gs'), 'colCount'), $col_count; is $ws->col_count, $col_count; is $ws->row_count($row_count), $row_count, "changing row_count to $row_count"; - is $ws->atom->get($ws->gsns, 'rowCount'), $row_count; + is $ws->atom->get($ws->service->ns('gs'), 'rowCount'), $row_count; is $ws->row_count, $row_count; } } { my $ws = $spreadsheet->worksheet({title => $args->{title}}); my @before = $spreadsheet->worksheets; ok grep {$_->id eq $ws->id} @before; ok grep {$_->title eq $ws->title} @before; ok $ws->delete, 'deleting worksheet'; my @ws = $spreadsheet->worksheets; is scalar @ws, (scalar @before) - 1, '(worksheet count)--'; ok ! grep({$_->id eq $ws->id} @ws), 'id disappeared'; ok ! grep({$_->title eq $ws->title} @ws), 'title disappeared'; is $spreadsheet->worksheet({title => $args->{title}}), undef, "shouldn't be able to get the worksheet"; } done_testing;
lopnor/Net-Google-Spreadsheets
06f8a8438b99936202b88d2428d639eb4e09e7d7
moving to Net::Google::GData
diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index 8dc72f2..620e253 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,271 +1,272 @@ package Net::Google::Spreadsheets; use Moose; +use Net::Google::GData; use namespace::clean -except => 'meta'; use 5.008001; -with - 'Net::Google::Spreadsheets::Role::Base', - 'Net::Google::Spreadsheets::Role::Service'; - our $VERSION = '0.06'; -has spreadsheet_feed => ( - traits => ['Net::Google::Spreadsheets::Traits::Feed'], - is => 'ro', - isa => 'Str', +with 'Net::Google::GData::Role::Service' => { + service => 'wise', + source => __PACKAGE__.'-'.$VERSION, + ns => { + gs => 'http://schemas.google.com/spreadsheets/2006', + gsx => 'http://schemas.google.com/spreadsheets/2006/extended', + batch => 'http://schemas.google.com/gdata/batch', + } +}; + +feedurl spreadsheet => ( default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full', entry_class => 'Net::Google::Spreadsheets::Spreadsheet', + can_add => 0, ); __PACKAGE__->meta->make_immutable; -sub _build_service {return $_[0]} - -sub _build_source { return __PACKAGE__. '-' . $VERSION } - 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, {row => 1, col => 4, input_value => 'age'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # fetch rows my @rows = $worksheet->rows; # or fetch rows with query @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); # delete the row $row->delete; # delete the worksheet $worksheet->delete; # create a table my $table = $spreadsheet->add_table( { worksheet => $new_worksheet, columns => ['name', 'nick', 'mail address', 'age'], } ); # add a record my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', 'mail address' => '[email protected]', age => '33', } ); # find a record my $found = $table->record( { sq => '"mail address" = "[email protected]"' } ); # delete it $found->delete; # delete table $table->delete; =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 4 =item username Username for Google. This should be full email address format like '[email protected]'. =item password Password corresponding to the username. =item source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 4 =item title title of the spreadsheet. =item title-exact whether title search should match exactly or not. =item key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 TESTING To test this module, you have to prepare as below. =over 4 =item create a spreadsheet by hand Go to L<http://docs.google.com> and create a spreadsheet. =item set SPREADSHEET_TITLE environment variable export SPREADSHEET_TITLE='my test spreadsheet' or so. =item set username and password for google.com via Config::Pit install Config::Pit and type ppit set google.com then some editor comes up and type your username and password like --- username: [email protected] password: foobarbaz =item run tests as always, perl Makefile.PL make make test =back =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Record> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Net/Google/Spreadsheets/Spreadsheet.pm b/lib/Net/Google/Spreadsheets/Spreadsheet.pm index ad68b6b..ca28354 100644 --- a/lib/Net/Google/Spreadsheets/Spreadsheet.pm +++ b/lib/Net/Google/Spreadsheets/Spreadsheet.pm @@ -1,245 +1,231 @@ package Net::Google::Spreadsheets::Spreadsheet; use Moose; use namespace::clean -except => 'meta'; +use Net::Google::GData; -with 'Net::Google::Spreadsheets::Role::Base'; +with 'Net::Google::GData::Role::Entry'; use Path::Class; use URI; has +title => ( is => 'ro', ); has key => ( isa => 'Str', is => 'ro', ); -has worksheet_feed => ( - traits => ['Net::Google::Spreadsheets::Traits::Feed'], - is => 'rw', - isa => 'Str', +feedurl worksheet => ( entry_class => 'Net::Google::Spreadsheets::Worksheet', - from_atom => sub { - my ($self) = @_; - $self->{worksheet_feed} = $self->atom->content->elem->getAttribute('src'); - }, + as_content_src => 1, ); -has table_feed => ( - traits => ['Net::Google::Spreadsheets::Traits::Feed'], - is => 'rw', - isa => 'Str', +feedurl table => ( entry_class => 'Net::Google::Spreadsheets::Table', - required => 1, - lazy_build => 1, + rel => 'http://schemas.google.com/spreadsheets/2006#tablefeed', ); -sub _build_table_feed { - my $self = shift; - return sprintf('http://spreadsheets.google.com/feeds/%s/tables',$self->key); -} - after from_atom => sub { my ($self) = @_; $self->{key} = file(URI->new($self->id)->path)->basename; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Spreadsheet - Representation of spreadsheet. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # create a worksheet my $worksheet = $spreadsheet->add_worksheet( { title => 'foobar', col_count => 10, row_count => 100, } ); # list worksheets my @ws = $spreadsheet->worksheets; # find a worksheet my $ws = $spreadsheet->worksheet({title => 'fooba'}); # create a table my $table = $spreadsheet->add_table( { title => 'sample table', worksheet => $worksheet, columns => ['id', 'username', 'mail', 'password'], } ); # list tables my @t = $spreadsheet->tables; # find a worksheet my $t = $spreadsheet->table({title => 'sample table'}); =head1 METHODS =head2 worksheets(\%condition) Returns a list of Net::Google::Spreadsheets::Worksheet objects. Acceptable arguments are: =over 4 =item title =item title-exact =back =head2 worksheet(\%condition) Returns first item of worksheets(\%condition) if available. =head2 add_worksheet(\%attribuets) Creates new worksheet and returns a Net::Google::Spreadsheets::Worksheet object representing it. Arguments (all optional) are: =over 4 =item title =item col_count =item row_count =back =head2 tables(\%condition) Returns a list of Net::Google::Spreadsheets::Table objects. Acceptable arguments are: =over 4 =item title =item title-exact =back =head2 table(\%condition) Returns first item of tables(\%condition) if available. =head2 add_table(\%attribuets) Creates new table and returns a Net::Google::Spreadsheets::Table object representing it. Arguments are: =over 4 =item title (optional) =item summary (optional) =item worksheet Worksheet where the table lives. worksheet instance or the title. =item header (optional, default = 1) Row number of header =item start_row (optional, default = 2) The index of the first row of the data section. =item insertion_mode (optional, default = 'overwrite') Insertion mode. 'insert' inserts new row into the worksheet when creating record, 'overwrite' tries to use existing rows in the worksheet. =item columns Columns of the table. you can specify them as hashref, arrayref, arrayref of hashref. $ss->add_table( { worksheet => $ws, columns => [ {index => 1, name => 'foo'}, {index => 2, name => 'bar'}, {index => 3, name => 'baz'}, ], } ); $ss->add_table( { worksheet => $ws, columns => { A => 'foo', B => 'bar', C => 'baz', } } ); $ss->add_table( { worksheet => $ws, columns => ['foo', 'bar', 'baz'], } ); 'index' of the first case and hash key of the second case is column index of the worksheet. In the third case, the columns is automatically placed to the columns of the worksheet from 'A' to 'Z' order. =back =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Table> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut
lopnor/Net-Google-Spreadsheets
5266f082fed212e43e1ec2deb62275358f015a41
version++
diff --git a/Changes b/Changes index d6e1d0d..24c2bda 100644 --- a/Changes +++ b/Changes @@ -1,23 +1,26 @@ Revision history for Perl extension Net::Google::Spreadsheets +0.06 Thu Aug 20 23:21:35 2009 + - Refactored internals + 0.06_01 Mon Arg 16 16:01:27 2009 - Supports Google Spreadsheets API version 3.0 - Add table and record feeds supports - Better error handlings (no more redirects, captures xml parse error, and more) - Refactored internals 0.05 Sun Aug 15 09:47:50 2009 - Fix Moose attribute problem #48627 (thanks to Eric Celeste, IMALPASS) 0.04 Wed Apr 15 09:22:59 2009 - Updated POD (thanks to Mr. Grue) 0.03 Sun Apr 05 13:22:21 2009 - param method for Net::Google::Spreadsheets::Row (thanks to Mr. Grue) 0.02 Sat Apr 04 22:32:40 2009 - Crypt::SSLeay dependency - Better error message on login failure (thanks to Mr. Grue) 0.01 Tue Dec 16 23:52:25 2008 - original version diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index 1d788dc..8dc72f2 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,271 +1,271 @@ package Net::Google::Spreadsheets; use Moose; use namespace::clean -except => 'meta'; use 5.008001; with 'Net::Google::Spreadsheets::Role::Base', 'Net::Google::Spreadsheets::Role::Service'; -our $VERSION = '0.06_01'; +our $VERSION = '0.06'; has spreadsheet_feed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'ro', isa => 'Str', default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full', entry_class => 'Net::Google::Spreadsheets::Spreadsheet', ); __PACKAGE__->meta->make_immutable; sub _build_service {return $_[0]} sub _build_source { return __PACKAGE__. '-' . $VERSION } 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, {row => 1, col => 4, input_value => 'age'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # fetch rows my @rows = $worksheet->rows; # or fetch rows with query @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); # delete the row $row->delete; # delete the worksheet $worksheet->delete; # create a table my $table = $spreadsheet->add_table( { worksheet => $new_worksheet, columns => ['name', 'nick', 'mail address', 'age'], } ); # add a record my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', 'mail address' => '[email protected]', age => '33', } ); # find a record my $found = $table->record( { sq => '"mail address" = "[email protected]"' } ); # delete it $found->delete; # delete table $table->delete; =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 4 =item username Username for Google. This should be full email address format like '[email protected]'. =item password Password corresponding to the username. =item source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 4 =item title title of the spreadsheet. =item title-exact whether title search should match exactly or not. =item key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 TESTING To test this module, you have to prepare as below. =over 4 =item create a spreadsheet by hand Go to L<http://docs.google.com> and create a spreadsheet. =item set SPREADSHEET_TITLE environment variable export SPREADSHEET_TITLE='my test spreadsheet' or so. =item set username and password for google.com via Config::Pit install Config::Pit and type ppit set google.com then some editor comes up and type your username and password like --- username: [email protected] password: foobarbaz =item run tests as always, perl Makefile.PL make make test =back =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Record> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
lopnor/Net-Google-Spreadsheets
8807c3beb3537cad09d27e77a6fb44e4f9998034
base move to role
diff --git a/.gitignore b/.gitignore index 77e983e..941c1e9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,8 @@ MANIFEST.bak META.yml Makefile +Makefile.old blib inc pm_to_blib cover_db diff --git a/MANIFEST b/MANIFEST index 788a1ab..630928c 100644 --- a/MANIFEST +++ b/MANIFEST @@ -1,52 +1,52 @@ Changes inc/Module/Install.pm inc/Module/Install/AuthorTests.pm inc/Module/Install/Base.pm inc/Module/Install/Can.pm inc/Module/Install/Fetch.pm inc/Module/Install/Include.pm inc/Module/Install/Makefile.pm inc/Module/Install/Metadata.pm -inc/Module/Install/Repository.pm inc/Module/Install/TestBase.pm inc/Module/Install/Win32.pm inc/Module/Install/WriteAll.pm inc/Spiffy.pm inc/Test/Base.pm inc/Test/Base/Filter.pm inc/Test/Builder.pm inc/Test/Builder/Module.pm inc/Test/Exception.pm inc/Test/MockModule.pm inc/Test/MockObject.pm inc/Test/More.pm lib/Net/Google/Spreadsheets.pm -lib/Net/Google/Spreadsheets/Base.pm lib/Net/Google/Spreadsheets/Cell.pm lib/Net/Google/Spreadsheets/Record.pm +lib/Net/Google/Spreadsheets/Role/Base.pm lib/Net/Google/Spreadsheets/Role/HasContent.pm +lib/Net/Google/Spreadsheets/Role/Service.pm lib/Net/Google/Spreadsheets/Row.pm lib/Net/Google/Spreadsheets/Spreadsheet.pm lib/Net/Google/Spreadsheets/Table.pm lib/Net/Google/Spreadsheets/Traits/Feed.pm lib/Net/Google/Spreadsheets/UserAgent.pm lib/Net/Google/Spreadsheets/Worksheet.pm Makefile.PL MANIFEST This list of files META.yml README t/00_compile.t t/01_instanciate.t t/02_spreadsheet.t t/03_worksheet.t t/04_cell.t t/05_row.t t/06_table.t t/07_record.t t/08_error.t t/Util.pm xt/01_podspell.t xt/02_perlcritic.t xt/03_pod.t xt/04_synopsis.t xt/perlcriticrc diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index dc979de..1d788dc 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,317 +1,271 @@ package Net::Google::Spreadsheets; use Moose; use namespace::clean -except => 'meta'; use 5.008001; -extends 'Net::Google::Spreadsheets::Base'; - -use Carp; -use Net::Google::AuthSub; -use Net::Google::Spreadsheets::UserAgent; +with + 'Net::Google::Spreadsheets::Role::Base', + 'Net::Google::Spreadsheets::Role::Service'; our $VERSION = '0.06_01'; -BEGIN { - $XML::Atom::DefaultVersion = 1; -} - has spreadsheet_feed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'ro', isa => 'Str', default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full', entry_class => 'Net::Google::Spreadsheets::Spreadsheet', ); -sub _build_service {return $_[0]} - -has source => ( - isa => 'Str', - is => 'ro', - required => 1, - default => sub { __PACKAGE__.'-'.$VERSION }, -); - -has username => ( isa => 'Str', is => 'ro', required => 1 ); -has password => ( isa => 'Str', is => 'ro', required => 1 ); - -has ua => ( - isa => 'Net::Google::Spreadsheets::UserAgent', - is => 'ro', - handles => [qw(request feed entry post put)], - required => 1, - lazy_build => 1, -); - -sub _build_ua { - my $self = shift; - my $authsub = Net::Google::AuthSub->new( - service => 'wise', - source => $self->source, - ); - my $res = $authsub->login( - $self->username, - $self->password, - ); - unless ($res && $res->is_success) { - croak 'Net::Google::AuthSub login failed'; - } - return Net::Google::Spreadsheets::UserAgent->new( - source => $self->source, - auth => $res->auth, - ); -} - __PACKAGE__->meta->make_immutable; -sub BUILD { - my ($self) = @_; - $self->ua; #check if login ok? -} +sub _build_service {return $_[0]} + +sub _build_source { return __PACKAGE__. '-' . $VERSION } 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, {row => 1, col => 4, input_value => 'age'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # fetch rows my @rows = $worksheet->rows; # or fetch rows with query @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); # delete the row $row->delete; # delete the worksheet $worksheet->delete; # create a table my $table = $spreadsheet->add_table( { worksheet => $new_worksheet, columns => ['name', 'nick', 'mail address', 'age'], } ); # add a record my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', 'mail address' => '[email protected]', age => '33', } ); # find a record my $found = $table->record( { sq => '"mail address" = "[email protected]"' } ); # delete it $found->delete; # delete table $table->delete; =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 4 =item username Username for Google. This should be full email address format like '[email protected]'. =item password Password corresponding to the username. =item source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 4 =item title title of the spreadsheet. =item title-exact whether title search should match exactly or not. =item key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 TESTING To test this module, you have to prepare as below. =over 4 =item create a spreadsheet by hand Go to L<http://docs.google.com> and create a spreadsheet. =item set SPREADSHEET_TITLE environment variable export SPREADSHEET_TITLE='my test spreadsheet' or so. =item set username and password for google.com via Config::Pit install Config::Pit and type ppit set google.com then some editor comes up and type your username and password like --- username: [email protected] password: foobarbaz =item run tests as always, perl Makefile.PL make make test =back =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Record> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Net/Google/Spreadsheets/Cell.pm b/lib/Net/Google/Spreadsheets/Cell.pm index b10100a..a379b9c 100644 --- a/lib/Net/Google/Spreadsheets/Cell.pm +++ b/lib/Net/Google/Spreadsheets/Cell.pm @@ -1,122 +1,122 @@ package Net::Google::Spreadsheets::Cell; use Moose; use namespace::clean -except => 'meta'; use XML::Atom::Util qw(first); -extends 'Net::Google::Spreadsheets::Base'; +with 'Net::Google::Spreadsheets::Role::Base'; has content => ( isa => 'Str', is => 'ro', ); has row => ( isa => 'Int', is => 'ro', ); has col => ( isa => 'Int', is => 'ro', ); has input_value => ( isa => 'Str', is => 'rw', trigger => sub {$_[0]->update}, ); after from_atom => sub { my ($self) = @_; my $elem = first( $self->elem, $self->gsns->{uri}, 'cell'); $self->{row} = $elem->getAttribute('row'); $self->{col} = $elem->getAttribute('col'); $self->{input_value} = $elem->getAttribute('inputValue'); $self->{content} = $elem->textContent || ''; }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->gsns, 'cell', '', { row => $self->row, col => $self->col, inputValue => $self->input_value, } ); my $link = XML::Atom::Link->new; $link->rel('edit'); $link->type('application/atom+xml'); $link->href($self->editurl); $entry->link($link); $entry->id($self->id); return $entry; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Cell - A representation class for Google Spreadsheet cell. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a cell my $cell = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->cell( { col => 1, row => 1, } ); # update a cell $cell->input_value('new value'); # get the content of a cell my $value = $cell->content; =head1 ATTRIBUTES =head2 input_value Rewritable attribute. You can set formula like '=A1+B1' or so. =head2 content Read only attribute. You can get the result of formula. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Record.pm b/lib/Net/Google/Spreadsheets/Record.pm index c33a8ac..b481b01 100644 --- a/lib/Net/Google/Spreadsheets/Record.pm +++ b/lib/Net/Google/Spreadsheets/Record.pm @@ -1,116 +1,117 @@ package Net::Google::Spreadsheets::Record; use Moose; use namespace::clean -except => 'meta'; use XML::Atom::Util qw(nodelist); -extends 'Net::Google::Spreadsheets::Base'; -with 'Net::Google::Spreadsheets::Role::HasContent'; +with + 'Net::Google::Spreadsheets::Role::Base', + 'Net::Google::Spreadsheets::Role::HasContent'; after from_atom => sub { my ($self) = @_; for my $node (nodelist($self->elem, $self->gsns->{uri}, 'field')) { $self->{content}->{$node->getAttribute('name')} = $node->textContent; } }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->{content}}) { $entry->add($self->gsns, 'field', $value, {name => $key}); } return $entry; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Record - A representation class for Google Spreadsheet record. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a record my $record = $service->spreadsheet( { title => 'list for new year cards', } )->table( { title => 'addressbook', } )->record( { sq => 'id = 1000', } ); # get the content of a row my $hashref = $record->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $record->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $record->param('name'); # returns 'Nobuo Danjou' my $newval = $record->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new record value (with all fields) my $hashref2 = $record->param; # same as $record->content; =head1 METHODS =head2 param sets and gets content value. =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Row> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Base.pm b/lib/Net/Google/Spreadsheets/Role/Base.pm similarity index 82% rename from lib/Net/Google/Spreadsheets/Base.pm rename to lib/Net/Google/Spreadsheets/Role/Base.pm index 30c7a73..0c710cd 100644 --- a/lib/Net/Google/Spreadsheets/Base.pm +++ b/lib/Net/Google/Spreadsheets/Role/Base.pm @@ -1,148 +1,127 @@ -package Net::Google::Spreadsheets::Base; -use Moose; +package Net::Google::Spreadsheets::Role::Base; +use Moose::Role; use namespace::clean -except => 'meta'; use Carp; has service => ( isa => 'Net::Google::Spreadsheets', is => 'ro', required => 1, lazy_build => 1, weak_ref => 1, ); sub _build_service { shift->container->service }; my %ns = ( gd => 'http://schemas.google.com/g/2005', gs => 'http://schemas.google.com/spreadsheets/2006', gsx => 'http://schemas.google.com/spreadsheets/2006/extended', batch => 'http://schemas.google.com/gdata/batch', ); while (my ($prefix, $uri) = each %ns) { __PACKAGE__->meta->add_method( "${prefix}ns" => sub { XML::Atom::Namespace->new($prefix, $uri) } ); } my %rel2label = ( edit => 'editurl', self => 'selfurl', ); for (values %rel2label) { has $_ => (isa => 'Str', is => 'ro'); } has atom => ( isa => 'XML::Atom::Entry', is => 'rw', trigger => sub { my ($self, $arg) = @_; my $id = $self->atom->get($self->ns, 'id'); croak "can't set different id!" if $self->id && $self->id ne $id; $self->from_atom; }, handles => ['ns', 'elem', 'author'], ); has id => ( isa => 'Str', is => 'ro', ); has title => ( isa => 'Str', is => 'rw', default => 'untitled', trigger => sub {$_[0]->update} ); has etag => ( isa => 'Str', is => 'rw', ); has container => ( - isa => 'Maybe[Net::Google::Spreadsheets::Base]', + isa => 'Maybe[Net::Google::Spreadsheets::Role::Base]', is => 'ro', ); -__PACKAGE__->meta->make_immutable; - sub from_atom { my ($self) = @_; $self->{title} = $self->atom->title; $self->{id} = $self->atom->get($self->ns, 'id'); $self->etag($self->elem->getAttributeNS($self->gdns->{uri}, 'etag')); for ($self->atom->link) { my $label = $rel2label{$_->rel} or next; $self->{$label} = $_->href; } } sub to_atom { my ($self) = @_; + $XML::Atom::DefaultVersion = 1; my $entry = XML::Atom::Entry->new; $entry->title($self->title) if $self->title; return $entry; } sub sync { my ($self) = @_; my $entry = $self->service->entry($self->selfurl); $self->atom($entry); } sub update { my ($self) = @_; $self->etag or return; my $atom = $self->service->put( { self => $self, entry => $self->to_atom, } ); $self->container->sync; $self->atom($atom); } sub delete { my $self = shift; my $res = $self->service->request( { uri => $self->editurl, method => 'DELETE', header => {'If-Match' => $self->etag}, } ); $self->container->sync if $res->is_success; return $res->is_success; } 1; -__END__ - -=head1 NAME - -Net::Google::Spreadsheets::Base - Base class of Net::Google::Spreadsheets::*. - -=head1 SEE ALSO - -L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> - -L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> - -L<Net::Google::AuthSub> - -L<Net::Google::Spreadsheets> - -=head1 AUTHOR - -Nobuo Danjou E<lt>[email protected]<gt> - -=cut +__END__ diff --git a/lib/Net/Google/Spreadsheets/Role/Service.pm b/lib/Net/Google/Spreadsheets/Role/Service.pm new file mode 100644 index 0000000..55c9cfc --- /dev/null +++ b/lib/Net/Google/Spreadsheets/Role/Service.pm @@ -0,0 +1,50 @@ +package Net::Google::Spreadsheets::Role::Service; +use Moose::Role; + +use Carp; +use Net::Google::AuthSub; +use Net::Google::Spreadsheets::UserAgent; + +has source => ( + isa => 'Str', + is => 'ro', + required => 1, + lazy_build => 1, +); + +has username => ( isa => 'Str', is => 'ro', required => 1 ); +has password => ( isa => 'Str', is => 'ro', required => 1 ); + +has ua => ( + isa => 'Net::Google::Spreadsheets::UserAgent', + is => 'ro', + handles => [qw(request feed entry post put)], + required => 1, + lazy_build => 1, +); + +sub _build_ua { + my $self = shift; + my $authsub = Net::Google::AuthSub->new( + service => 'wise', + source => $self->source, + ); + my $res = $authsub->login( + $self->username, + $self->password, + ); + unless ($res && $res->is_success) { + croak 'Net::Google::AuthSub login failed'; + } + return Net::Google::Spreadsheets::UserAgent->new( + source => $self->source, + auth => $res->auth, + ); +} + +sub BUILD { + my ($self) = @_; + $self->ua; #check if login ok? +} + +1; diff --git a/lib/Net/Google/Spreadsheets/Row.pm b/lib/Net/Google/Spreadsheets/Row.pm index a25f371..3f28259 100644 --- a/lib/Net/Google/Spreadsheets/Row.pm +++ b/lib/Net/Google/Spreadsheets/Row.pm @@ -1,168 +1,169 @@ package Net::Google::Spreadsheets::Row; use Moose; use namespace::clean -except => 'meta'; use XML::Atom::Util qw(nodelist); -extends 'Net::Google::Spreadsheets::Base'; -with 'Net::Google::Spreadsheets::Role::HasContent'; +with + 'Net::Google::Spreadsheets::Role::Base', + 'Net::Google::Spreadsheets::Role::HasContent'; after from_atom => sub { my ($self) = @_; for my $node (nodelist($self->elem, $self->gsxns->{uri}, '*')) { $self->{content}->{$node->localname} = $node->textContent; } }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->{content}}) { $entry->set($self->gsxns, $key, $value); } return $entry; }; __PACKAGE__->meta->make_immutable; sub param { my ($self, $arg) = @_; return $self->content unless $arg; if (ref $arg && (ref $arg eq 'HASH')) { return $self->content( { %{$self->content}, %$arg, } ); } else { return $self->content->{$arg}; } } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Row - A representation class for Google Spreadsheet row. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a row my $row = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->row( { sq => 'id = 1000' } ); # get the content of a row my $hashref = $row->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $row->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $row->param('name'); # returns 'Nobuo Danjou' my $newval = $row->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new row value (with all fields) my $hashref2 = $row->param; # same as $row->content; =head1 METHODS =head2 param sets and gets content value. =head1 CAVEATS Space characters in hash key of rows will be removed when you access rows. See below. my $ws = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'})->worksheet(1); $ws->batchupdate_cell( {col => 1,row => 1, input_value => 'name'}, {col => 2,row => 1, input_value => 'mail address'}, ); $ws->add_row( { name => 'my name', mailaddress => '[email protected]', # above passes, below fails. # 'mail address' => '[email protected]', } ); Instead, Net::Google::Spreadsheets::Table and Net::Google::Spreadsheets::Record allows space characters in column name. my $s = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'}); my $t = $s->add_table( { worksheet => $s->worksheet(1), columns => ['name', 'mail address'], } ); $t->add_record( { name => 'my name', 'mail address' => '[email protected]', } ); =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Spreadsheet.pm b/lib/Net/Google/Spreadsheets/Spreadsheet.pm index 3e0e4f1..ad68b6b 100644 --- a/lib/Net/Google/Spreadsheets/Spreadsheet.pm +++ b/lib/Net/Google/Spreadsheets/Spreadsheet.pm @@ -1,246 +1,245 @@ package Net::Google::Spreadsheets::Spreadsheet; use Moose; use namespace::clean -except => 'meta'; -extends 'Net::Google::Spreadsheets::Base'; +with 'Net::Google::Spreadsheets::Role::Base'; -use Net::Google::Spreadsheets::Worksheet; use Path::Class; use URI; has +title => ( is => 'ro', ); has key => ( isa => 'Str', is => 'ro', ); has worksheet_feed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'rw', isa => 'Str', entry_class => 'Net::Google::Spreadsheets::Worksheet', from_atom => sub { my ($self) = @_; $self->{worksheet_feed} = $self->atom->content->elem->getAttribute('src'); }, ); has table_feed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'rw', isa => 'Str', entry_class => 'Net::Google::Spreadsheets::Table', required => 1, lazy_build => 1, ); sub _build_table_feed { my $self = shift; return sprintf('http://spreadsheets.google.com/feeds/%s/tables',$self->key); } after from_atom => sub { my ($self) = @_; $self->{key} = file(URI->new($self->id)->path)->basename; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Spreadsheet - Representation of spreadsheet. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # create a worksheet my $worksheet = $spreadsheet->add_worksheet( { title => 'foobar', col_count => 10, row_count => 100, } ); # list worksheets my @ws = $spreadsheet->worksheets; # find a worksheet my $ws = $spreadsheet->worksheet({title => 'fooba'}); # create a table my $table = $spreadsheet->add_table( { title => 'sample table', worksheet => $worksheet, columns => ['id', 'username', 'mail', 'password'], } ); # list tables my @t = $spreadsheet->tables; # find a worksheet my $t = $spreadsheet->table({title => 'sample table'}); =head1 METHODS =head2 worksheets(\%condition) Returns a list of Net::Google::Spreadsheets::Worksheet objects. Acceptable arguments are: =over 4 =item title =item title-exact =back =head2 worksheet(\%condition) Returns first item of worksheets(\%condition) if available. =head2 add_worksheet(\%attribuets) Creates new worksheet and returns a Net::Google::Spreadsheets::Worksheet object representing it. Arguments (all optional) are: =over 4 =item title =item col_count =item row_count =back =head2 tables(\%condition) Returns a list of Net::Google::Spreadsheets::Table objects. Acceptable arguments are: =over 4 =item title =item title-exact =back =head2 table(\%condition) Returns first item of tables(\%condition) if available. =head2 add_table(\%attribuets) Creates new table and returns a Net::Google::Spreadsheets::Table object representing it. Arguments are: =over 4 =item title (optional) =item summary (optional) =item worksheet Worksheet where the table lives. worksheet instance or the title. =item header (optional, default = 1) Row number of header =item start_row (optional, default = 2) The index of the first row of the data section. =item insertion_mode (optional, default = 'overwrite') Insertion mode. 'insert' inserts new row into the worksheet when creating record, 'overwrite' tries to use existing rows in the worksheet. =item columns Columns of the table. you can specify them as hashref, arrayref, arrayref of hashref. $ss->add_table( { worksheet => $ws, columns => [ {index => 1, name => 'foo'}, {index => 2, name => 'bar'}, {index => 3, name => 'baz'}, ], } ); $ss->add_table( { worksheet => $ws, columns => { A => 'foo', B => 'bar', C => 'baz', } } ); $ss->add_table( { worksheet => $ws, columns => ['foo', 'bar', 'baz'], } ); 'index' of the first case and hash key of the second case is column index of the worksheet. In the third case, the columns is automatically placed to the columns of the worksheet from 'A' to 'Z' order. =back =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Table> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Table.pm b/lib/Net/Google/Spreadsheets/Table.pm index cccb48a..b2c8583 100644 --- a/lib/Net/Google/Spreadsheets/Table.pm +++ b/lib/Net/Google/Spreadsheets/Table.pm @@ -1,232 +1,233 @@ package Net::Google::Spreadsheets::Table; use Moose; use Moose::Util::TypeConstraints; use namespace::clean -except => 'meta'; use XML::Atom::Util qw(nodelist first create_element); +with 'Net::Google::Spreadsheets::Role::Base'; + subtype 'ColumnList' => as 'ArrayRef[Net::Google::Spreadsheets::Table::Column]'; coerce 'ColumnList' => from 'ArrayRef[HashRef]' => via { [ map {Net::Google::Spreadsheets::Table::Column->new($_)} @$_ ] }; coerce 'ColumnList' => from 'ArrayRef[Str]' => via { my @c; my $index = 0; for my $value (@$_) { push @c, Net::Google::Spreadsheets::Table::Column->new( index => ++$index, name => $value, ); } \@c; }; coerce 'ColumnList' => from 'HashRef' => via { my @c; while (my ($key, $value) = each(%$_)) { push @c, Net::Google::Spreadsheets::Table::Column->new( index => $key, name => $value, ); } \@c; }; subtype 'WorksheetName' => as 'Str'; coerce 'WorksheetName' => from 'Net::Google::Spreadsheets::Worksheet' => via { $_->title }; -extends 'Net::Google::Spreadsheets::Base'; has record_feed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'ro', isa => 'Str', entry_class => 'Net::Google::Spreadsheets::Record', entry_arg_builder => sub { my ($self, $args) = @_; return {content => $args}; }, from_atom => sub { my $self = shift; $self->{record_feed} = first($self->elem, '', 'content')->getAttribute('src'); }, ); has summary => ( is => 'rw', isa => 'Str' ); has worksheet => ( is => 'ro', isa => 'WorksheetName', coerce => 1 ); has header => ( is => 'ro', isa => 'Int', required => 1, default => 1 ); has start_row => ( is => 'ro', isa => 'Int', required => 1, default => 2 ); has num_rows => ( is => 'ro', isa => 'Int' ); has columns => ( is => 'ro', isa => 'ColumnList', coerce => 1 ); has insertion_mode => ( is => 'ro', isa => (enum ['insert', 'overwrite']), default => 'overwrite' ); after from_atom => sub { my ($self) = @_; my $gsns = $self->gsns->{uri}; my $elem = $self->elem; $self->{summary} = $self->atom->summary; $self->{worksheet} = first( $elem, $gsns, 'worksheet')->getAttribute('name'); $self->{header} = first( $elem, $gsns, 'header')->getAttribute('row'); my @columns; my $data = first($elem, $gsns, 'data'); $self->{insertion_mode} = $data->getAttribute('insertionMode'); $self->{start_row} = $data->getAttribute('startRow'); $self->{num_rows} = $data->getAttribute('numRows'); for (nodelist($data, $gsns, 'column')) { push @columns, Net::Google::Spreadsheets::Table::Column->new( index => $_->getAttribute('index'), name => $_->getAttribute('name'), ); } $self->{columns} = \@columns; }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->summary($self->summary) if $self->summary; $entry->set($self->gsns, 'worksheet', '', {name => $self->worksheet}); $entry->set($self->gsns, 'header', '', {row => $self->header}); my $data = create_element($self->gsns, 'data'); $data->setAttribute(startRow => $self->start_row); $data->setAttribute(insertionMode => $self->insertion_mode); $data->setAttribute(startRow => $self->start_row) if $self->start_row; for ( @{$self->columns} ) { my $column = create_element($self->gsns, 'column'); $column->setAttribute(index => $_->index); $column->setAttribute(name => $_->name); $data->appendChild($column); } $entry->set($self->gsns, 'data', $data); return $entry; }; __PACKAGE__->meta->make_immutable; package # hide from PAUSE Net::Google::Spreadsheets::Table::Column; use Moose; has 'index' => ( is => 'ro', isa => 'Str' ); has 'name' => ( is => 'ro', isa => 'Str' ); __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Table - A representation class for Google Spreadsheet table. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a table my $table = $service->spreadsheet( { title => 'list for new year cards', } )->table( { title => 'sample table', } ); # create a record my $r = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # get records my @records = $table->records; # search records @records = $table->records({sq => 'age > 20'}); # search a record my $record = $table->record({sq => 'name = "Nobuo Danjou"'}); =head1 METHODS =head2 records(\%condition) Returns a list of Net::Google::Spreadsheets::Record objects. Acceptable arguments are: =over 4 =item sq Structured query on the full text in the worksheet. see the URL below for detail. =item orderby Set column name to use for ordering. =item reverse Set 'true' or 'false'. The default is 'false'. =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#RecordParameters> for details. =head2 record(\%condition) Returns first item of records(\%condition) if available. =head2 add_record(\%contents) Creates new record and returns a Net::Google::Spreadsheets::Record object representing it. Arguments are contents of a row as a hashref. my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Record> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/UserAgent.pm b/lib/Net/Google/Spreadsheets/UserAgent.pm index 64f374e..ac2fab2 100644 --- a/lib/Net/Google/Spreadsheets/UserAgent.pm +++ b/lib/Net/Google/Spreadsheets/UserAgent.pm @@ -1,147 +1,154 @@ package Net::Google::Spreadsheets::UserAgent; use Moose; use namespace::clean -except => 'meta'; use Carp; use LWP::UserAgent; -use HTTP::Headers; -use HTTP::Request; use URI; use XML::Atom::Entry; use XML::Atom::Feed; has source => ( isa => 'Str', is => 'ro', required => 1, ); has auth => ( isa => 'Str', is => 'rw', required => 1, ); has ua => ( isa => 'LWP::UserAgent', is => 'ro', required => 1, lazy_build => 1, ); sub _build_ua { my $self = shift; my $ua = LWP::UserAgent->new( agent => $self->source, requests_redirectable => [], ); $ua->default_headers( HTTP::Headers->new( Authorization => sprintf('GoogleLogin auth=%s', $self->auth), GData_Version => '3.0', ) ); return $ua; } __PACKAGE__->meta->make_immutable; sub request { my ($self, $args) = @_; my $method = delete $args->{method}; $method ||= $args->{content} ? 'POST' : 'GET'; my $uri = URI->new($args->{'uri'}); $uri->query_form($args->{query}) if $args->{query}; my $req = HTTP::Request->new($method => "$uri"); $req->content($args->{content}) if $args->{content}; $req->header('Content-Type' => $args->{content_type}) if $args->{content_type}; if ($args->{header}) { while (my @pair = each %{$args->{header}}) { $req->header(@pair); } } my $res = eval {$self->ua->request($req)}; + if ($ENV{DEBUG}) { + warn $res->request->as_string; + warn $res->as_string; + } if ($@ || !$res->is_success) { - die sprintf("request for '%s' failed:\n\t%s\n\t%s\n\t", $uri, ($@ || $res->status_line), ($! || $res->content)); + die sprintf( + "request for '%s' failed:\n\t%s\n\t%s\n\t", + $uri, + $@ || $res->status_line, + $! || $res->content + ); } my $type = $res->content_type; if ($res->content_length && $type !~ m{^application/atom\+xml}) { die sprintf("Content-Type of response for '%s' is not 'application/atom+xml': %s", $uri, $type); } if (my $res_obj = $args->{response_object}) { my $obj = eval {$res_obj->new(\($res->content))}; croak sprintf("response for '%s' is broken: %s", $uri, $@) if $@; return $obj; } return $res; } sub feed { my ($self, $url, $query) = @_; return $self->request( { uri => $url, query => $query || undef, response_object => 'XML::Atom::Feed', } ); } sub entry { my ($self, $url, $query) = @_; return $self->request( { uri => $url, query => $query || undef, response_object => 'XML::Atom::Entry', } ); } sub post { my ($self, $url, $entry, $header) = @_; return $self->request( { uri => $url, content => $entry->as_xml, header => $header || undef, content_type => 'application/atom+xml', response_object => ref $entry, } ); } sub put { my ($self, $args) = @_; return $self->request( { method => 'PUT', uri => $args->{self}->editurl, content => $args->{entry}->as_xml, header => {'If-Match' => $args->{self}->etag }, content_type => 'application/atom+xml', response_object => 'XML::Atom::Entry', } ); } 1; __END__ =head1 NAME Net::Google::Spreadsheets::UserAgent - UserAgent for Net::Google::Spreadsheets. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Worksheet.pm b/lib/Net/Google/Spreadsheets/Worksheet.pm index 887789e..dcbc5e5 100644 --- a/lib/Net/Google/Spreadsheets/Worksheet.pm +++ b/lib/Net/Google/Spreadsheets/Worksheet.pm @@ -1,268 +1,269 @@ package Net::Google::Spreadsheets::Worksheet; use Moose; use Carp; use namespace::clean -except => 'meta'; -extends 'Net::Google::Spreadsheets::Base'; +with 'Net::Google::Spreadsheets::Role::Base'; use Net::Google::Spreadsheets::Cell; +use XML::Atom::Util qw(first); has row_feed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'ro', isa => 'Str', entry_class => 'Net::Google::Spreadsheets::Row', entry_arg_builder => sub { my ($self, $args) = @_; return {content => $args}; }, from_atom => sub { my $self = shift; $self->{row_feed} = $self->atom->content->elem->getAttribute('src'); }, ); has cellsfeed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'ro', isa => 'Str', entry_class => 'Net::Google::Spreadsheets::Cell', entry_arg_builder => sub { my ($self, $args) = @_; croak 'you can\'t call add_cell!'; }, query_arg_builder => sub { my ($self, $args) = @_; if (my $col = delete $args->{col}) { $args->{'max-col'} = $col; $args->{'min-col'} = $col; $args->{'return-empty'} = 'true'; } if (my $row = delete $args->{row}) { $args->{'max-row'} = $row; $args->{'min-row'} = $row; $args->{'return-empty'} = 'true'; } return $args; }, from_atom => sub { my ($self) = @_; ($self->{cellsfeed}) = map {$_->href} grep { $_->rel eq 'http://schemas.google.com/spreadsheets/2006#cellsfeed' } $self->atom->link; } ); has row_count => ( isa => 'Int', is => 'rw', default => 100, trigger => sub {$_[0]->update} ); has col_count => ( isa => 'Int', is => 'rw', default => 20, trigger => sub {$_[0]->update} ); around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->gsns, 'rowCount', $self->row_count); $entry->set($self->gsns, 'colCount', $self->col_count); return $entry; }; after from_atom => sub { my ($self) = @_; $self->{row_count} = $self->atom->get($self->gsns, 'rowCount'); $self->{col_count} = $self->atom->get($self->gsns, 'colCount'); }; __PACKAGE__->meta->make_immutable; sub batchupdate_cell { my ($self, @args) = @_; my $feed = XML::Atom::Feed->new; for ( @args ) { my $id = sprintf("%s/R%sC%s",$self->cellsfeed, $_->{row}, $_->{col}); $_->{id} = $_->{editurl} = $id; my $entry = Net::Google::Spreadsheets::Cell->new($_)->to_atom; $entry->set($self->batchns, operation => '', {type => 'update'}); $entry->set($self->batchns, id => $id); $feed->add_entry($entry); } my $res_feed = $self->service->post($self->cellsfeed."/batch", $feed, {'If-Match' => '*'}); $self->sync; return map { Net::Google::Spreadsheets::Cell->new( atom => $_, container => $self, ) } grep { - my $node = XML::Atom::Util::first( + my $node = first( $_->elem, $self->batchns->{uri}, 'status' ); $node->getAttribute('code') == 200; } $res_feed->entries; } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Worksheet - Representation of worksheet. =head1 SYNOPSIS my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); my $ss = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); my $worksheet = $ss->worksheet({title => 'Sheet1'}); # update cell by batch request $worksheet->batchupdate_cell( {col => 1, row => 1, input_value => 'name'}, {col => 2, row => 1, input_value => 'nick'}, {col => 3, row => 1, input_value => 'mail'}, {col => 4, row => 1, input_value => 'age'}, ); # get a cell object my $cell = $worksheet->cell({col => 1, row => 1}); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # get rows my @rows = $worksheet->rows; # search rows @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); =head1 METHODS =head2 rows(\%condition) Returns a list of Net::Google::Spreadsheets::Row objects. Acceptable arguments are: =over 4 =item sq Structured query on the full text in the worksheet. see the URL below for detail. =item orderby Set column name to use for ordering. =item reverse Set 'true' or 'false'. The default is 'false'. =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#ListParameters> for details. =head2 row(\%condition) Returns first item of rows(\%condition) if available. =head2 add_row(\%contents) Creates new row and returns a Net::Google::Spreadsheets::Row object representing it. Arguments are contents of a row as a hashref. my $row = $ws->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); =head2 cells(\%args) Returns a list of Net::Google::Spreadsheets::Cell objects. Acceptable arguments are: =over 4 =item min-row =item max-row =item min-col =item max-col =item range =item return-empty =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#CellParameters> for details. =head2 cell(\%args) Returns Net::Google::Spreadsheets::Cell object. Arguments are: =over 4 =item col =item row =back =head2 batchupdate_cell(@args) update multiple cells with a batch request. Pass a list of hash references containing: =over 4 =item col =item row =item input_value =back =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut
lopnor/Net-Google-Spreadsheets
c0795de709b3fbac4b5758699ba213c01cc60a0b
Checking in changes prior to tagging of version 0.06_01. Changelog diff is:
diff --git a/.gitignore b/.gitignore index cfbbf00..77e983e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ MANIFEST.bak META.yml Makefile blib inc pm_to_blib +cover_db diff --git a/Changes b/Changes index 4d6bfd2..d6e1d0d 100644 --- a/Changes +++ b/Changes @@ -1,17 +1,23 @@ Revision history for Perl extension Net::Google::Spreadsheets +0.06_01 Mon Arg 16 16:01:27 2009 + - Supports Google Spreadsheets API version 3.0 + - Add table and record feeds supports + - Better error handlings (no more redirects, captures xml parse error, and more) + - Refactored internals + 0.05 Sun Aug 15 09:47:50 2009 - - Fix Moose attribute problem #48627(thanks to Eric Celeste, IMALPASS) + - Fix Moose attribute problem #48627 (thanks to Eric Celeste, IMALPASS) 0.04 Wed Apr 15 09:22:59 2009 - Updated POD (thanks to Mr. Grue) 0.03 Sun Apr 05 13:22:21 2009 - param method for Net::Google::Spreadsheets::Row (thanks to Mr. Grue) 0.02 Sat Apr 04 22:32:40 2009 - Crypt::SSLeay dependency - Better error message on login failure (thanks to Mr. Grue) 0.01 Tue Dec 16 23:52:25 2008 - original version diff --git a/MANIFEST b/MANIFEST index afd0080..788a1ab 100644 --- a/MANIFEST +++ b/MANIFEST @@ -1,50 +1,52 @@ Changes inc/Module/Install.pm inc/Module/Install/AuthorTests.pm inc/Module/Install/Base.pm inc/Module/Install/Can.pm inc/Module/Install/Fetch.pm inc/Module/Install/Include.pm inc/Module/Install/Makefile.pm inc/Module/Install/Metadata.pm +inc/Module/Install/Repository.pm inc/Module/Install/TestBase.pm inc/Module/Install/Win32.pm inc/Module/Install/WriteAll.pm inc/Spiffy.pm inc/Test/Base.pm inc/Test/Base/Filter.pm inc/Test/Builder.pm inc/Test/Builder/Module.pm inc/Test/Exception.pm inc/Test/MockModule.pm inc/Test/MockObject.pm inc/Test/More.pm lib/Net/Google/Spreadsheets.pm lib/Net/Google/Spreadsheets/Base.pm lib/Net/Google/Spreadsheets/Cell.pm lib/Net/Google/Spreadsheets/Record.pm lib/Net/Google/Spreadsheets/Role/HasContent.pm lib/Net/Google/Spreadsheets/Row.pm lib/Net/Google/Spreadsheets/Spreadsheet.pm lib/Net/Google/Spreadsheets/Table.pm lib/Net/Google/Spreadsheets/Traits/Feed.pm lib/Net/Google/Spreadsheets/UserAgent.pm lib/Net/Google/Spreadsheets/Worksheet.pm Makefile.PL MANIFEST This list of files META.yml README t/00_compile.t t/01_instanciate.t t/02_spreadsheet.t t/03_worksheet.t t/04_cell.t t/05_row.t t/06_table.t t/07_record.t t/08_error.t t/Util.pm xt/01_podspell.t xt/02_perlcritic.t xt/03_pod.t +xt/04_synopsis.t xt/perlcriticrc diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index 652b3fc..dc979de 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,317 +1,317 @@ package Net::Google::Spreadsheets; use Moose; use namespace::clean -except => 'meta'; use 5.008001; extends 'Net::Google::Spreadsheets::Base'; use Carp; use Net::Google::AuthSub; use Net::Google::Spreadsheets::UserAgent; -our $VERSION = '0.05'; +our $VERSION = '0.06_01'; BEGIN { $XML::Atom::DefaultVersion = 1; } has spreadsheet_feed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'ro', isa => 'Str', default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full', entry_class => 'Net::Google::Spreadsheets::Spreadsheet', ); sub _build_service {return $_[0]} has source => ( isa => 'Str', is => 'ro', required => 1, default => sub { __PACKAGE__.'-'.$VERSION }, ); has username => ( isa => 'Str', is => 'ro', required => 1 ); has password => ( isa => 'Str', is => 'ro', required => 1 ); has ua => ( isa => 'Net::Google::Spreadsheets::UserAgent', is => 'ro', handles => [qw(request feed entry post put)], required => 1, lazy_build => 1, ); sub _build_ua { my $self = shift; my $authsub = Net::Google::AuthSub->new( service => 'wise', source => $self->source, ); my $res = $authsub->login( $self->username, $self->password, ); unless ($res && $res->is_success) { croak 'Net::Google::AuthSub login failed'; } return Net::Google::Spreadsheets::UserAgent->new( source => $self->source, auth => $res->auth, ); } __PACKAGE__->meta->make_immutable; sub BUILD { my ($self) = @_; $self->ua; #check if login ok? } 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, {row => 1, col => 4, input_value => 'age'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # fetch rows my @rows = $worksheet->rows; # or fetch rows with query @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); # delete the row $row->delete; # delete the worksheet $worksheet->delete; # create a table my $table = $spreadsheet->add_table( { worksheet => $new_worksheet, columns => ['name', 'nick', 'mail address', 'age'], } ); # add a record my $record = $table->add_record( { name => 'Nobuo Danjou', nick => 'lopnor', 'mail address' => '[email protected]', age => '33', } ); # find a record my $found = $table->record( { sq => '"mail address" = "[email protected]"' } ); # delete it $found->delete; # delete table $table->delete; =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 4 =item username Username for Google. This should be full email address format like '[email protected]'. =item password Password corresponding to the username. =item source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 4 =item title title of the spreadsheet. =item title-exact whether title search should match exactly or not. =item key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 TESTING To test this module, you have to prepare as below. =over 4 =item create a spreadsheet by hand Go to L<http://docs.google.com> and create a spreadsheet. =item set SPREADSHEET_TITLE environment variable export SPREADSHEET_TITLE='my test spreadsheet' or so. =item set username and password for google.com via Config::Pit install Config::Pit and type ppit set google.com then some editor comes up and type your username and password like --- username: [email protected] password: foobarbaz =item run tests as always, perl Makefile.PL make make test =back =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Record> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Net/Google/Spreadsheets/Record.pm b/lib/Net/Google/Spreadsheets/Record.pm index af05bab..c33a8ac 100644 --- a/lib/Net/Google/Spreadsheets/Record.pm +++ b/lib/Net/Google/Spreadsheets/Record.pm @@ -1,116 +1,116 @@ package Net::Google::Spreadsheets::Record; use Moose; use namespace::clean -except => 'meta'; use XML::Atom::Util qw(nodelist); extends 'Net::Google::Spreadsheets::Base'; with 'Net::Google::Spreadsheets::Role::HasContent'; after from_atom => sub { my ($self) = @_; for my $node (nodelist($self->elem, $self->gsns->{uri}, 'field')) { $self->{content}->{$node->getAttribute('name')} = $node->textContent; } }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->{content}}) { $entry->add($self->gsns, 'field', $value, {name => $key}); } return $entry; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Record - A representation class for Google Spreadsheet record. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a record my $record = $service->spreadsheet( { title => 'list for new year cards', } )->table( { title => 'addressbook', } )->record( { sq => 'id = 1000', } ); # get the content of a row my $hashref = $record->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $record->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $record->param('name'); # returns 'Nobuo Danjou' my $newval = $record->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new record value (with all fields) - my $hashref = $record->param; + my $hashref2 = $record->param; # same as $record->content; =head1 METHODS =head2 param sets and gets content value. =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> L<Net::Google::Spreadsheets::Table> L<Net::Google::Spreadsheets::Row> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Row.pm b/lib/Net/Google/Spreadsheets/Row.pm index 01e87f2..a25f371 100644 --- a/lib/Net/Google/Spreadsheets/Row.pm +++ b/lib/Net/Google/Spreadsheets/Row.pm @@ -1,168 +1,168 @@ package Net::Google::Spreadsheets::Row; use Moose; use namespace::clean -except => 'meta'; use XML::Atom::Util qw(nodelist); extends 'Net::Google::Spreadsheets::Base'; with 'Net::Google::Spreadsheets::Role::HasContent'; after from_atom => sub { my ($self) = @_; for my $node (nodelist($self->elem, $self->gsxns->{uri}, '*')) { $self->{content}->{$node->localname} = $node->textContent; } }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->{content}}) { $entry->set($self->gsxns, $key, $value); } return $entry; }; __PACKAGE__->meta->make_immutable; sub param { my ($self, $arg) = @_; return $self->content unless $arg; if (ref $arg && (ref $arg eq 'HASH')) { return $self->content( { %{$self->content}, %$arg, } ); } else { return $self->content->{$arg}; } } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Row - A representation class for Google Spreadsheet row. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a row my $row = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->row( { sq => 'id = 1000' } ); # get the content of a row my $hashref = $row->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $row->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $row->param('name'); # returns 'Nobuo Danjou' my $newval = $row->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new row value (with all fields) - my $hashref = $row->param; + my $hashref2 = $row->param; # same as $row->content; =head1 METHODS =head2 param sets and gets content value. =head1 CAVEATS Space characters in hash key of rows will be removed when you access rows. See below. my $ws = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'})->worksheet(1); $ws->batchupdate_cell( {col => 1,row => 1, input_value => 'name'}, {col => 2,row => 1, input_value => 'mail address'}, ); $ws->add_row( { name => 'my name', mailaddress => '[email protected]', # above passes, below fails. # 'mail address' => '[email protected]', } ); Instead, Net::Google::Spreadsheets::Table and Net::Google::Spreadsheets::Record allows space characters in column name. my $s = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'}); my $t = $s->add_table( { worksheet => $s->worksheet(1), columns => ['name', 'mail address'], } ); $t->add_record( { name => 'my name', 'mail address' => '[email protected]', } ); =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Spreadsheet.pm b/lib/Net/Google/Spreadsheets/Spreadsheet.pm index 45d2f2c..3e0e4f1 100644 --- a/lib/Net/Google/Spreadsheets/Spreadsheet.pm +++ b/lib/Net/Google/Spreadsheets/Spreadsheet.pm @@ -1,119 +1,246 @@ package Net::Google::Spreadsheets::Spreadsheet; use Moose; use namespace::clean -except => 'meta'; extends 'Net::Google::Spreadsheets::Base'; use Net::Google::Spreadsheets::Worksheet; use Path::Class; use URI; has +title => ( is => 'ro', ); has key => ( isa => 'Str', is => 'ro', ); has worksheet_feed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'rw', isa => 'Str', entry_class => 'Net::Google::Spreadsheets::Worksheet', from_atom => sub { my ($self) = @_; $self->{worksheet_feed} = $self->atom->content->elem->getAttribute('src'); }, ); has table_feed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'rw', isa => 'Str', entry_class => 'Net::Google::Spreadsheets::Table', + required => 1, lazy_build => 1, ); sub _build_table_feed { my $self = shift; return sprintf('http://spreadsheets.google.com/feeds/%s/tables',$self->key); } after from_atom => sub { my ($self) = @_; $self->{key} = file(URI->new($self->id)->path)->basename; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Spreadsheet - Representation of spreadsheet. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); + # create a worksheet + my $worksheet = $spreadsheet->add_worksheet( + { + title => 'foobar', + col_count => 10, + row_count => 100, + } + ); + + # list worksheets + my @ws = $spreadsheet->worksheets; + # find a worksheet + my $ws = $spreadsheet->worksheet({title => 'fooba'}); + + # create a table + my $table = $spreadsheet->add_table( + { + title => 'sample table', + worksheet => $worksheet, + columns => ['id', 'username', 'mail', 'password'], + } + ); + + # list tables + my @t = $spreadsheet->tables; + # find a worksheet + my $t = $spreadsheet->table({title => 'sample table'}); + + =head1 METHODS =head2 worksheets(\%condition) Returns a list of Net::Google::Spreadsheets::Worksheet objects. Acceptable arguments are: =over 4 =item title =item title-exact =back =head2 worksheet(\%condition) Returns first item of worksheets(\%condition) if available. =head2 add_worksheet(\%attribuets) -Creates new worksheet and returns a Net::Google::Spreadsheets::Worksheet object representing it. +Creates new worksheet and returns a Net::Google::Spreadsheets::Worksheet object representing it. +Arguments (all optional) are: + +=over 4 + +=item title + +=item col_count + +=item row_count + +=back + +=head2 tables(\%condition) + +Returns a list of Net::Google::Spreadsheets::Table objects. Acceptable arguments are: + +=over 4 + +=item title + +=item title-exact + +=back + +=head2 table(\%condition) + +Returns first item of tables(\%condition) if available. + +=head2 add_table(\%attribuets) + +Creates new table and returns a Net::Google::Spreadsheets::Table object representing it. +Arguments are: + +=over 4 + +=item title (optional) + +=item summary (optional) + +=item worksheet + +Worksheet where the table lives. worksheet instance or the title. + +=item header (optional, default = 1) + +Row number of header + +=item start_row (optional, default = 2) + +The index of the first row of the data section. + +=item insertion_mode (optional, default = 'overwrite') + +Insertion mode. 'insert' inserts new row into the worksheet when creating record, 'overwrite' tries to use existing rows in the worksheet. + +=item columns + +Columns of the table. you can specify them as hashref, arrayref, arrayref of hashref. + + $ss->add_table( + { + worksheet => $ws, + columns => [ + {index => 1, name => 'foo'}, + {index => 2, name => 'bar'}, + {index => 3, name => 'baz'}, + ], + } + ); + + $ss->add_table( + { + worksheet => $ws, + columns => { + A => 'foo', + B => 'bar', + C => 'baz', + } + } + ); + + $ss->add_table( + { + worksheet => $ws, + columns => ['foo', 'bar', 'baz'], + } + ); + +'index' of the first case and hash key of the second case is column index of the worksheet. +In the third case, the columns is automatically placed to the columns of the worksheet +from 'A' to 'Z' order. + +=back =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> +L<Net::Google::Spreadsheets::Worksheet> + +L<Net::Google::Spreadsheets::Table> + =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Table.pm b/lib/Net/Google/Spreadsheets/Table.pm index 3d85272..cccb48a 100644 --- a/lib/Net/Google/Spreadsheets/Table.pm +++ b/lib/Net/Google/Spreadsheets/Table.pm @@ -1,230 +1,232 @@ package Net::Google::Spreadsheets::Table; use Moose; use Moose::Util::TypeConstraints; use namespace::clean -except => 'meta'; use XML::Atom::Util qw(nodelist first create_element); subtype 'ColumnList' - => as 'ArrayRef[Net::Google::Spreadsheets::Column]'; + => as 'ArrayRef[Net::Google::Spreadsheets::Table::Column]'; coerce 'ColumnList' => from 'ArrayRef[HashRef]' => via { - [ map {Net::Google::Spreadsheets::Column->new($_)} @$_ ] + [ map {Net::Google::Spreadsheets::Table::Column->new($_)} @$_ ] }; coerce 'ColumnList' => from 'ArrayRef[Str]' => via { my @c; my $index = 0; for my $value (@$_) { - push @c, Net::Google::Spreadsheets::Column->new( + push @c, Net::Google::Spreadsheets::Table::Column->new( index => ++$index, name => $value, ); } \@c; }; coerce 'ColumnList' => from 'HashRef' => via { my @c; while (my ($key, $value) = each(%$_)) { - push @c, Net::Google::Spreadsheets::Column->new( + push @c, Net::Google::Spreadsheets::Table::Column->new( index => $key, name => $value, ); } \@c; }; subtype 'WorksheetName' => as 'Str'; coerce 'WorksheetName' => from 'Net::Google::Spreadsheets::Worksheet' => via { $_->title }; extends 'Net::Google::Spreadsheets::Base'; has record_feed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'ro', isa => 'Str', entry_class => 'Net::Google::Spreadsheets::Record', entry_arg_builder => sub { my ($self, $args) = @_; return {content => $args}; }, from_atom => sub { my $self = shift; $self->{record_feed} = first($self->elem, '', 'content')->getAttribute('src'); }, ); has summary => ( is => 'rw', isa => 'Str' ); has worksheet => ( is => 'ro', isa => 'WorksheetName', coerce => 1 ); has header => ( is => 'ro', isa => 'Int', required => 1, default => 1 ); has start_row => ( is => 'ro', isa => 'Int', required => 1, default => 2 ); has num_rows => ( is => 'ro', isa => 'Int' ); has columns => ( is => 'ro', isa => 'ColumnList', coerce => 1 ); has insertion_mode => ( is => 'ro', isa => (enum ['insert', 'overwrite']), default => 'overwrite' ); after from_atom => sub { my ($self) = @_; my $gsns = $self->gsns->{uri}; my $elem = $self->elem; $self->{summary} = $self->atom->summary; $self->{worksheet} = first( $elem, $gsns, 'worksheet')->getAttribute('name'); $self->{header} = first( $elem, $gsns, 'header')->getAttribute('row'); my @columns; my $data = first($elem, $gsns, 'data'); $self->{insertion_mode} = $data->getAttribute('insertionMode'); $self->{start_row} = $data->getAttribute('startRow'); $self->{num_rows} = $data->getAttribute('numRows'); for (nodelist($data, $gsns, 'column')) { - push @columns, Net::Google::Spreadsheets::Column->new( + push @columns, Net::Google::Spreadsheets::Table::Column->new( index => $_->getAttribute('index'), name => $_->getAttribute('name'), ); } $self->{columns} = \@columns; }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->summary($self->summary) if $self->summary; $entry->set($self->gsns, 'worksheet', '', {name => $self->worksheet}); $entry->set($self->gsns, 'header', '', {row => $self->header}); my $data = create_element($self->gsns, 'data'); $data->setAttribute(startRow => $self->start_row); $data->setAttribute(insertionMode => $self->insertion_mode); $data->setAttribute(startRow => $self->start_row) if $self->start_row; for ( @{$self->columns} ) { my $column = create_element($self->gsns, 'column'); $column->setAttribute(index => $_->index); $column->setAttribute(name => $_->name); $data->appendChild($column); } $entry->set($self->gsns, 'data', $data); return $entry; }; __PACKAGE__->meta->make_immutable; package # hide from PAUSE - Net::Google::Spreadsheets::Column; + Net::Google::Spreadsheets::Table::Column; use Moose; has 'index' => ( is => 'ro', isa => 'Str' ); has 'name' => ( is => 'ro', isa => 'Str' ); __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Table - A representation class for Google Spreadsheet table. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); - # get a row - my $row = $service->spreadsheet( + # get a table + my $table = $service->spreadsheet( { title => 'list for new year cards', } - )->worksheet( + )->table( { - title => 'Sheet1', - } - )->row( - { - sq => 'id = 1000' + title => 'sample table', } ); - # get the content of a row - my $hashref = $row->content; - my $id = $hashref->{id}; - my $address = $hashref->{address}; - - # update a row - $row->content( + # create a record + my $r = $table->add_record( { - id => 1000, - address => 'somewhere', - zip => '100-0001', name => 'Nobuo Danjou', + nick => 'lopnor', + mail => '[email protected]', + age => '33', } ); - # get and set values partially - - my $value = $row->param('name'); - # returns 'Nobuo Danjou' - - my $newval = $row->param({address => 'elsewhere'}); - # updates address (and keeps other fields) and returns new row value (with all fields) + # get records + my @records = $table->records; - my $hashref = $row->param; - # same as $row->content; + # search records + @records = $table->records({sq => 'age > 20'}); + + # search a record + my $record = $table->record({sq => 'name = "Nobuo Danjou"'}); =head1 METHODS -=head2 param +=head2 records(\%condition) -sets and gets content value. +Returns a list of Net::Google::Spreadsheets::Record objects. Acceptable arguments are: -=head1 CAVEATS +=over 4 -Space characters in hash key of rows will be removed when you access rows. See below. +=item sq - my $ws = Net::Google::Spreadsheets->new( - username => '[email protected]', - password => 'foobar' - )->spreadsheet({titile => 'sample'})->worksheet(1); - $ws->batchupdate_cell( - {col => 1,row => 1, input_value => 'name'}, - {col => 2,row => 1, input_value => 'mail address'}, - ); - $ws->add_row( - { - name => 'my name', - mailaddress => '[email protected]', - # above passes, below fails. - # 'mail address' => '[email protected]', - } - ); +Structured query on the full text in the worksheet. see the URL below for detail. + +=item orderby + +Set column name to use for ordering. + +=item reverse -=head1 ATTRIBUTES +Set 'true' or 'false'. The default is 'false'. -=head2 content +=back -Rewritable attribute. You can get and set the value. +See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#RecordParameters> for details. + +=head2 record(\%condition) + +Returns first item of records(\%condition) if available. + +=head2 add_record(\%contents) + +Creates new record and returns a Net::Google::Spreadsheets::Record object representing it. +Arguments are contents of a row as a hashref. + + my $record = $table->add_record( + { + name => 'Nobuo Danjou', + nick => 'lopnor', + mail => '[email protected]', + age => '33', + } + ); =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> +L<Net::Google::Spreadsheets::Spreadsheet> + +L<Net::Google::Spreadsheets::Record> + =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Worksheet.pm b/lib/Net/Google/Spreadsheets/Worksheet.pm index 9184ffd..887789e 100644 --- a/lib/Net/Google/Spreadsheets/Worksheet.pm +++ b/lib/Net/Google/Spreadsheets/Worksheet.pm @@ -1,254 +1,268 @@ package Net::Google::Spreadsheets::Worksheet; use Moose; use Carp; use namespace::clean -except => 'meta'; extends 'Net::Google::Spreadsheets::Base'; use Net::Google::Spreadsheets::Cell; has row_feed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'ro', isa => 'Str', entry_class => 'Net::Google::Spreadsheets::Row', entry_arg_builder => sub { my ($self, $args) = @_; return {content => $args}; }, from_atom => sub { my $self = shift; $self->{row_feed} = $self->atom->content->elem->getAttribute('src'); }, ); has cellsfeed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'ro', isa => 'Str', entry_class => 'Net::Google::Spreadsheets::Cell', entry_arg_builder => sub { my ($self, $args) = @_; croak 'you can\'t call add_cell!'; }, query_arg_builder => sub { my ($self, $args) = @_; if (my $col = delete $args->{col}) { $args->{'max-col'} = $col; $args->{'min-col'} = $col; $args->{'return-empty'} = 'true'; } if (my $row = delete $args->{row}) { $args->{'max-row'} = $row; $args->{'min-row'} = $row; $args->{'return-empty'} = 'true'; } return $args; }, from_atom => sub { my ($self) = @_; ($self->{cellsfeed}) = map {$_->href} grep { $_->rel eq 'http://schemas.google.com/spreadsheets/2006#cellsfeed' } $self->atom->link; } ); has row_count => ( isa => 'Int', is => 'rw', default => 100, trigger => sub {$_[0]->update} ); has col_count => ( isa => 'Int', is => 'rw', default => 20, trigger => sub {$_[0]->update} ); around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->gsns, 'rowCount', $self->row_count); $entry->set($self->gsns, 'colCount', $self->col_count); return $entry; }; after from_atom => sub { my ($self) = @_; $self->{row_count} = $self->atom->get($self->gsns, 'rowCount'); $self->{col_count} = $self->atom->get($self->gsns, 'colCount'); }; __PACKAGE__->meta->make_immutable; sub batchupdate_cell { my ($self, @args) = @_; my $feed = XML::Atom::Feed->new; for ( @args ) { my $id = sprintf("%s/R%sC%s",$self->cellsfeed, $_->{row}, $_->{col}); $_->{id} = $_->{editurl} = $id; my $entry = Net::Google::Spreadsheets::Cell->new($_)->to_atom; $entry->set($self->batchns, operation => '', {type => 'update'}); $entry->set($self->batchns, id => $id); $feed->add_entry($entry); } my $res_feed = $self->service->post($self->cellsfeed."/batch", $feed, {'If-Match' => '*'}); $self->sync; return map { Net::Google::Spreadsheets::Cell->new( atom => $_, container => $self, ) } grep { my $node = XML::Atom::Util::first( $_->elem, $self->batchns->{uri}, 'status' ); $node->getAttribute('code') == 200; } $res_feed->entries; } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Worksheet - Representation of worksheet. =head1 SYNOPSIS my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); my $ss = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); my $worksheet = $ss->worksheet({title => 'Sheet1'}); # update cell by batch request $worksheet->batchupdate_cell( {col => 1, row => 1, input_value => 'name'}, {col => 2, row => 1, input_value => 'nick'}, {col => 3, row => 1, input_value => 'mail'}, {col => 4, row => 1, input_value => 'age'}, ); # get a cell object my $cell = $worksheet->cell({col => 1, row => 1}); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # get rows my @rows = $worksheet->rows; # search rows @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); =head1 METHODS =head2 rows(\%condition) Returns a list of Net::Google::Spreadsheets::Row objects. Acceptable arguments are: =over 4 =item sq Structured query on the full text in the worksheet. see the URL below for detail. =item orderby Set column name to use for ordering. =item reverse Set 'true' or 'false'. The default is 'false'. =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#ListParameters> for details. =head2 row(\%condition) -Returns first item of spreadsheets(\%condition) if available. +Returns first item of rows(\%condition) if available. + +=head2 add_row(\%contents) + +Creates new row and returns a Net::Google::Spreadsheets::Row object representing it. Arguments are +contents of a row as a hashref. + + my $row = $ws->add_row( + { + name => 'Nobuo Danjou', + nick => 'lopnor', + mail => '[email protected]', + age => '33', + } + ); =head2 cells(\%args) Returns a list of Net::Google::Spreadsheets::Cell objects. Acceptable arguments are: =over 4 =item min-row =item max-row =item min-col =item max-col =item range =item return-empty =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#CellParameters> for details. =head2 cell(\%args) Returns Net::Google::Spreadsheets::Cell object. Arguments are: =over 4 =item col =item row =back =head2 batchupdate_cell(@args) update multiple cells with a batch request. Pass a list of hash references containing: =over 4 =item col =item row =item input_value =back =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut
lopnor/Net-Google-Spreadsheets
194f1f91bdc1fc0b634dcc1a58166b6ae60e4447
reference url change to v3.0
diff --git a/Makefile.PL b/Makefile.PL index e87f078..b2037c3 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,23 +1,24 @@ use inc::Module::Install; name 'Net-Google-Spreadsheets'; all_from 'lib/Net/Google/Spreadsheets.pm'; requires 'Carp'; requires 'XML::Atom'; requires 'Net::Google::AuthSub'; requires 'Crypt::SSLeay'; requires 'LWP::UserAgent'; requires 'URI'; requires 'Moose' => 0.34; requires 'Path::Class'; tests 't/*.t'; author_tests 'xt'; build_requires 'Test::More' => '0.88'; build_requires 'Test::Exception'; build_requires 'Test::MockModule'; build_requires 'Test::MockObject'; use_test_base; auto_include; +auto_set_repository; WriteAll; diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index e36c031..652b3fc 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,276 +1,317 @@ package Net::Google::Spreadsheets; use Moose; use namespace::clean -except => 'meta'; use 5.008001; extends 'Net::Google::Spreadsheets::Base'; use Carp; use Net::Google::AuthSub; use Net::Google::Spreadsheets::UserAgent; our $VERSION = '0.05'; BEGIN { $XML::Atom::DefaultVersion = 1; } has spreadsheet_feed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'ro', isa => 'Str', default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full', entry_class => 'Net::Google::Spreadsheets::Spreadsheet', ); sub _build_service {return $_[0]} has source => ( isa => 'Str', is => 'ro', required => 1, default => sub { __PACKAGE__.'-'.$VERSION }, ); has username => ( isa => 'Str', is => 'ro', required => 1 ); has password => ( isa => 'Str', is => 'ro', required => 1 ); has ua => ( isa => 'Net::Google::Spreadsheets::UserAgent', is => 'ro', handles => [qw(request feed entry post put)], required => 1, lazy_build => 1, ); sub _build_ua { my $self = shift; my $authsub = Net::Google::AuthSub->new( service => 'wise', source => $self->source, ); my $res = $authsub->login( $self->username, $self->password, ); unless ($res && $res->is_success) { croak 'Net::Google::AuthSub login failed'; } return Net::Google::Spreadsheets::UserAgent->new( source => $self->source, auth => $res->auth, ); } __PACKAGE__->meta->make_immutable; sub BUILD { my ($self) = @_; $self->ua; #check if login ok? } 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, {row => 1, col => 4, input_value => 'age'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # fetch rows my @rows = $worksheet->rows; # or fetch rows with query @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); + # delete the row + $row->delete; + + # delete the worksheet + $worksheet->delete; + + # create a table + my $table = $spreadsheet->add_table( + { + worksheet => $new_worksheet, + columns => ['name', 'nick', 'mail address', 'age'], + } + ); + + # add a record + my $record = $table->add_record( + { + name => 'Nobuo Danjou', + nick => 'lopnor', + 'mail address' => '[email protected]', + age => '33', + } + ); + + # find a record + my $found = $table->record( + { + sq => '"mail address" = "[email protected]"' + } + ); + + # delete it + $found->delete; + + # delete table + $table->delete; + =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 4 =item username Username for Google. This should be full email address format like '[email protected]'. =item password Password corresponding to the username. =item source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 4 =item title title of the spreadsheet. =item title-exact whether title search should match exactly or not. =item key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 TESTING To test this module, you have to prepare as below. =over 4 =item create a spreadsheet by hand Go to L<http://docs.google.com> and create a spreadsheet. =item set SPREADSHEET_TITLE environment variable export SPREADSHEET_TITLE='my test spreadsheet' or so. =item set username and password for google.com via Config::Pit install Config::Pit and type ppit set google.com then some editor comes up and type your username and password like --- username: [email protected] password: foobarbaz =item run tests as always, perl Makefile.PL make make test =back =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO -L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> +L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> -L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> +L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> +L<Net::Google::Spreadsheets::Table> + +L<Net::Google::Spreadsheets::Record> + =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Net/Google/Spreadsheets/Base.pm b/lib/Net/Google/Spreadsheets/Base.pm index e97fa42..30c7a73 100644 --- a/lib/Net/Google/Spreadsheets/Base.pm +++ b/lib/Net/Google/Spreadsheets/Base.pm @@ -1,148 +1,148 @@ package Net::Google::Spreadsheets::Base; use Moose; use namespace::clean -except => 'meta'; use Carp; has service => ( isa => 'Net::Google::Spreadsheets', is => 'ro', required => 1, lazy_build => 1, weak_ref => 1, ); sub _build_service { shift->container->service }; my %ns = ( gd => 'http://schemas.google.com/g/2005', gs => 'http://schemas.google.com/spreadsheets/2006', gsx => 'http://schemas.google.com/spreadsheets/2006/extended', batch => 'http://schemas.google.com/gdata/batch', ); while (my ($prefix, $uri) = each %ns) { __PACKAGE__->meta->add_method( "${prefix}ns" => sub { XML::Atom::Namespace->new($prefix, $uri) } ); } my %rel2label = ( edit => 'editurl', self => 'selfurl', ); for (values %rel2label) { has $_ => (isa => 'Str', is => 'ro'); } has atom => ( isa => 'XML::Atom::Entry', is => 'rw', trigger => sub { my ($self, $arg) = @_; my $id = $self->atom->get($self->ns, 'id'); croak "can't set different id!" if $self->id && $self->id ne $id; $self->from_atom; }, handles => ['ns', 'elem', 'author'], ); has id => ( isa => 'Str', is => 'ro', ); has title => ( isa => 'Str', is => 'rw', default => 'untitled', trigger => sub {$_[0]->update} ); has etag => ( isa => 'Str', is => 'rw', ); has container => ( isa => 'Maybe[Net::Google::Spreadsheets::Base]', is => 'ro', ); __PACKAGE__->meta->make_immutable; sub from_atom { my ($self) = @_; $self->{title} = $self->atom->title; $self->{id} = $self->atom->get($self->ns, 'id'); $self->etag($self->elem->getAttributeNS($self->gdns->{uri}, 'etag')); for ($self->atom->link) { my $label = $rel2label{$_->rel} or next; $self->{$label} = $_->href; } } sub to_atom { my ($self) = @_; my $entry = XML::Atom::Entry->new; $entry->title($self->title) if $self->title; return $entry; } sub sync { my ($self) = @_; my $entry = $self->service->entry($self->selfurl); $self->atom($entry); } sub update { my ($self) = @_; $self->etag or return; my $atom = $self->service->put( { self => $self, entry => $self->to_atom, } ); $self->container->sync; $self->atom($atom); } sub delete { my $self = shift; my $res = $self->service->request( { uri => $self->editurl, method => 'DELETE', header => {'If-Match' => $self->etag}, } ); $self->container->sync if $res->is_success; return $res->is_success; } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Base - Base class of Net::Google::Spreadsheets::*. =head1 SEE ALSO -L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> +L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> -L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> +L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Cell.pm b/lib/Net/Google/Spreadsheets/Cell.pm index 4a5fdcd..b10100a 100644 --- a/lib/Net/Google/Spreadsheets/Cell.pm +++ b/lib/Net/Google/Spreadsheets/Cell.pm @@ -1,122 +1,122 @@ package Net::Google::Spreadsheets::Cell; use Moose; use namespace::clean -except => 'meta'; use XML::Atom::Util qw(first); extends 'Net::Google::Spreadsheets::Base'; has content => ( isa => 'Str', is => 'ro', ); has row => ( isa => 'Int', is => 'ro', ); has col => ( isa => 'Int', is => 'ro', ); has input_value => ( isa => 'Str', is => 'rw', trigger => sub {$_[0]->update}, ); after from_atom => sub { my ($self) = @_; my $elem = first( $self->elem, $self->gsns->{uri}, 'cell'); $self->{row} = $elem->getAttribute('row'); $self->{col} = $elem->getAttribute('col'); $self->{input_value} = $elem->getAttribute('inputValue'); $self->{content} = $elem->textContent || ''; }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->gsns, 'cell', '', { row => $self->row, col => $self->col, inputValue => $self->input_value, } ); my $link = XML::Atom::Link->new; $link->rel('edit'); $link->type('application/atom+xml'); $link->href($self->editurl); $entry->link($link); $entry->id($self->id); return $entry; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Cell - A representation class for Google Spreadsheet cell. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a cell my $cell = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->cell( { col => 1, row => 1, } ); # update a cell $cell->input_value('new value'); # get the content of a cell my $value = $cell->content; =head1 ATTRIBUTES =head2 input_value Rewritable attribute. You can set formula like '=A1+B1' or so. =head2 content Read only attribute. You can get the result of formula. =head1 SEE ALSO -L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> +L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> -L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> +L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Record.pm b/lib/Net/Google/Spreadsheets/Record.pm index 63ac0d5..af05bab 100644 --- a/lib/Net/Google/Spreadsheets/Record.pm +++ b/lib/Net/Google/Spreadsheets/Record.pm @@ -1,29 +1,116 @@ package Net::Google::Spreadsheets::Record; use Moose; use namespace::clean -except => 'meta'; use XML::Atom::Util qw(nodelist); extends 'Net::Google::Spreadsheets::Base'; with 'Net::Google::Spreadsheets::Role::HasContent'; after from_atom => sub { my ($self) = @_; for my $node (nodelist($self->elem, $self->gsns->{uri}, 'field')) { $self->{content}->{$node->getAttribute('name')} = $node->textContent; } }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->{content}}) { $entry->add($self->gsns, 'field', $value, {name => $key}); } return $entry; }; __PACKAGE__->meta->make_immutable; 1; __END__ + +=head1 NAME + +Net::Google::Spreadsheets::Record - A representation class for Google Spreadsheet record. + +=head1 SYNOPSIS + + use Net::Google::Spreadsheets; + + my $service = Net::Google::Spreadsheets->new( + username => '[email protected]', + password => 'mypassword', + ); + + # get a record + my $record = $service->spreadsheet( + { + title => 'list for new year cards', + } + )->table( + { + title => 'addressbook', + } + )->record( + { + sq => 'id = 1000', + } + ); + + # get the content of a row + my $hashref = $record->content; + my $id = $hashref->{id}; + my $address = $hashref->{address}; + + # update a row + $record->content( + { + id => 1000, + address => 'somewhere', + zip => '100-0001', + name => 'Nobuo Danjou', + } + ); + + # get and set values partially + + my $value = $record->param('name'); + # returns 'Nobuo Danjou' + + my $newval = $record->param({address => 'elsewhere'}); + # updates address (and keeps other fields) and returns new record value (with all fields) + + my $hashref = $record->param; + # same as $record->content; + +=head1 METHODS + +=head2 param + +sets and gets content value. + +=head1 ATTRIBUTES + +=head2 content + +Rewritable attribute. You can get and set the value. + +=head1 SEE ALSO + +L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> + +L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> + +L<Net::Google::AuthSub> + +L<Net::Google::Spreadsheets> + +L<Net::Google::Spreadsheets::Table> + +L<Net::Google::Spreadsheets::Row> + +=head1 AUTHOR + +Nobuo Danjou E<lt>[email protected]<gt> + +=cut + diff --git a/lib/Net/Google/Spreadsheets/Row.pm b/lib/Net/Google/Spreadsheets/Row.pm index 261781a..01e87f2 100644 --- a/lib/Net/Google/Spreadsheets/Row.pm +++ b/lib/Net/Google/Spreadsheets/Row.pm @@ -1,147 +1,168 @@ package Net::Google::Spreadsheets::Row; use Moose; use namespace::clean -except => 'meta'; use XML::Atom::Util qw(nodelist); extends 'Net::Google::Spreadsheets::Base'; with 'Net::Google::Spreadsheets::Role::HasContent'; after from_atom => sub { my ($self) = @_; for my $node (nodelist($self->elem, $self->gsxns->{uri}, '*')) { $self->{content}->{$node->localname} = $node->textContent; } }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->{content}}) { $entry->set($self->gsxns, $key, $value); } return $entry; }; __PACKAGE__->meta->make_immutable; sub param { my ($self, $arg) = @_; return $self->content unless $arg; if (ref $arg && (ref $arg eq 'HASH')) { return $self->content( { %{$self->content}, %$arg, } ); } else { return $self->content->{$arg}; } } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Row - A representation class for Google Spreadsheet row. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a row my $row = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->row( { sq => 'id = 1000' } ); # get the content of a row my $hashref = $row->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $row->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $row->param('name'); # returns 'Nobuo Danjou' my $newval = $row->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new row value (with all fields) my $hashref = $row->param; # same as $row->content; =head1 METHODS =head2 param sets and gets content value. =head1 CAVEATS Space characters in hash key of rows will be removed when you access rows. See below. my $ws = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'})->worksheet(1); $ws->batchupdate_cell( {col => 1,row => 1, input_value => 'name'}, {col => 2,row => 1, input_value => 'mail address'}, ); $ws->add_row( { name => 'my name', mailaddress => '[email protected]', # above passes, below fails. # 'mail address' => '[email protected]', } ); +Instead, Net::Google::Spreadsheets::Table and Net::Google::Spreadsheets::Record allows +space characters in column name. + + my $s = Net::Google::Spreadsheets->new( + username => '[email protected]', + password => 'foobar' + )->spreadsheet({titile => 'sample'}); + + my $t = $s->add_table( + { + worksheet => $s->worksheet(1), + columns => ['name', 'mail address'], + } + ); + $t->add_record( + { + name => 'my name', + 'mail address' => '[email protected]', + } + ); + =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO -L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> +L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> -L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> +L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Spreadsheet.pm b/lib/Net/Google/Spreadsheets/Spreadsheet.pm index 3fb2886..45d2f2c 100644 --- a/lib/Net/Google/Spreadsheets/Spreadsheet.pm +++ b/lib/Net/Google/Spreadsheets/Spreadsheet.pm @@ -1,119 +1,119 @@ package Net::Google::Spreadsheets::Spreadsheet; use Moose; use namespace::clean -except => 'meta'; extends 'Net::Google::Spreadsheets::Base'; use Net::Google::Spreadsheets::Worksheet; use Path::Class; use URI; has +title => ( is => 'ro', ); has key => ( isa => 'Str', is => 'ro', ); has worksheet_feed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'rw', isa => 'Str', entry_class => 'Net::Google::Spreadsheets::Worksheet', from_atom => sub { my ($self) = @_; $self->{worksheet_feed} = $self->atom->content->elem->getAttribute('src'); }, ); has table_feed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'rw', isa => 'Str', entry_class => 'Net::Google::Spreadsheets::Table', lazy_build => 1, ); sub _build_table_feed { my $self = shift; return sprintf('http://spreadsheets.google.com/feeds/%s/tables',$self->key); } after from_atom => sub { my ($self) = @_; $self->{key} = file(URI->new($self->id)->path)->basename; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Spreadsheet - Representation of spreadsheet. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); =head1 METHODS =head2 worksheets(\%condition) Returns a list of Net::Google::Spreadsheets::Worksheet objects. Acceptable arguments are: =over 4 =item title =item title-exact =back =head2 worksheet(\%condition) Returns first item of worksheets(\%condition) if available. =head2 add_worksheet(\%attribuets) Creates new worksheet and returns a Net::Google::Spreadsheets::Worksheet object representing it. =head1 SEE ALSO -L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> +L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> -L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> +L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/UserAgent.pm b/lib/Net/Google/Spreadsheets/UserAgent.pm index 7d0d84c..64f374e 100644 --- a/lib/Net/Google/Spreadsheets/UserAgent.pm +++ b/lib/Net/Google/Spreadsheets/UserAgent.pm @@ -1,147 +1,147 @@ package Net::Google::Spreadsheets::UserAgent; use Moose; use namespace::clean -except => 'meta'; use Carp; use LWP::UserAgent; use HTTP::Headers; use HTTP::Request; use URI; use XML::Atom::Entry; use XML::Atom::Feed; has source => ( isa => 'Str', is => 'ro', required => 1, ); has auth => ( isa => 'Str', is => 'rw', required => 1, ); has ua => ( isa => 'LWP::UserAgent', is => 'ro', required => 1, lazy_build => 1, ); sub _build_ua { my $self = shift; my $ua = LWP::UserAgent->new( agent => $self->source, requests_redirectable => [], ); $ua->default_headers( HTTP::Headers->new( Authorization => sprintf('GoogleLogin auth=%s', $self->auth), GData_Version => '3.0', ) ); return $ua; } __PACKAGE__->meta->make_immutable; sub request { my ($self, $args) = @_; my $method = delete $args->{method}; $method ||= $args->{content} ? 'POST' : 'GET'; my $uri = URI->new($args->{'uri'}); $uri->query_form($args->{query}) if $args->{query}; my $req = HTTP::Request->new($method => "$uri"); $req->content($args->{content}) if $args->{content}; $req->header('Content-Type' => $args->{content_type}) if $args->{content_type}; if ($args->{header}) { while (my @pair = each %{$args->{header}}) { $req->header(@pair); } } my $res = eval {$self->ua->request($req)}; if ($@ || !$res->is_success) { die sprintf("request for '%s' failed:\n\t%s\n\t%s\n\t", $uri, ($@ || $res->status_line), ($! || $res->content)); } my $type = $res->content_type; if ($res->content_length && $type !~ m{^application/atom\+xml}) { die sprintf("Content-Type of response for '%s' is not 'application/atom+xml': %s", $uri, $type); } if (my $res_obj = $args->{response_object}) { my $obj = eval {$res_obj->new(\($res->content))}; croak sprintf("response for '%s' is broken: %s", $uri, $@) if $@; return $obj; } return $res; } sub feed { my ($self, $url, $query) = @_; return $self->request( { uri => $url, query => $query || undef, response_object => 'XML::Atom::Feed', } ); } sub entry { my ($self, $url, $query) = @_; return $self->request( { uri => $url, query => $query || undef, response_object => 'XML::Atom::Entry', } ); } sub post { my ($self, $url, $entry, $header) = @_; return $self->request( { uri => $url, content => $entry->as_xml, header => $header || undef, content_type => 'application/atom+xml', response_object => ref $entry, } ); } sub put { my ($self, $args) = @_; return $self->request( { method => 'PUT', uri => $args->{self}->editurl, content => $args->{entry}->as_xml, header => {'If-Match' => $args->{self}->etag }, content_type => 'application/atom+xml', response_object => 'XML::Atom::Entry', } ); } 1; __END__ =head1 NAME Net::Google::Spreadsheets::UserAgent - UserAgent for Net::Google::Spreadsheets. =head1 SEE ALSO -L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> +L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> -L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> +L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Worksheet.pm b/lib/Net/Google/Spreadsheets/Worksheet.pm index 56d3751..9184ffd 100644 --- a/lib/Net/Google/Spreadsheets/Worksheet.pm +++ b/lib/Net/Google/Spreadsheets/Worksheet.pm @@ -1,254 +1,254 @@ package Net::Google::Spreadsheets::Worksheet; use Moose; use Carp; use namespace::clean -except => 'meta'; extends 'Net::Google::Spreadsheets::Base'; use Net::Google::Spreadsheets::Cell; has row_feed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'ro', isa => 'Str', entry_class => 'Net::Google::Spreadsheets::Row', entry_arg_builder => sub { my ($self, $args) = @_; return {content => $args}; }, from_atom => sub { my $self = shift; $self->{row_feed} = $self->atom->content->elem->getAttribute('src'); }, ); has cellsfeed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'ro', isa => 'Str', entry_class => 'Net::Google::Spreadsheets::Cell', entry_arg_builder => sub { my ($self, $args) = @_; croak 'you can\'t call add_cell!'; }, query_arg_builder => sub { my ($self, $args) = @_; if (my $col = delete $args->{col}) { $args->{'max-col'} = $col; $args->{'min-col'} = $col; $args->{'return-empty'} = 'true'; } if (my $row = delete $args->{row}) { $args->{'max-row'} = $row; $args->{'min-row'} = $row; $args->{'return-empty'} = 'true'; } return $args; }, from_atom => sub { my ($self) = @_; ($self->{cellsfeed}) = map {$_->href} grep { $_->rel eq 'http://schemas.google.com/spreadsheets/2006#cellsfeed' } $self->atom->link; } ); has row_count => ( isa => 'Int', is => 'rw', default => 100, trigger => sub {$_[0]->update} ); has col_count => ( isa => 'Int', is => 'rw', default => 20, trigger => sub {$_[0]->update} ); around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->gsns, 'rowCount', $self->row_count); $entry->set($self->gsns, 'colCount', $self->col_count); return $entry; }; after from_atom => sub { my ($self) = @_; $self->{row_count} = $self->atom->get($self->gsns, 'rowCount'); $self->{col_count} = $self->atom->get($self->gsns, 'colCount'); }; __PACKAGE__->meta->make_immutable; sub batchupdate_cell { my ($self, @args) = @_; my $feed = XML::Atom::Feed->new; for ( @args ) { my $id = sprintf("%s/R%sC%s",$self->cellsfeed, $_->{row}, $_->{col}); $_->{id} = $_->{editurl} = $id; my $entry = Net::Google::Spreadsheets::Cell->new($_)->to_atom; $entry->set($self->batchns, operation => '', {type => 'update'}); $entry->set($self->batchns, id => $id); $feed->add_entry($entry); } my $res_feed = $self->service->post($self->cellsfeed."/batch", $feed, {'If-Match' => '*'}); $self->sync; return map { Net::Google::Spreadsheets::Cell->new( atom => $_, container => $self, ) } grep { my $node = XML::Atom::Util::first( $_->elem, $self->batchns->{uri}, 'status' ); $node->getAttribute('code') == 200; } $res_feed->entries; } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Worksheet - Representation of worksheet. =head1 SYNOPSIS my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); my $ss = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); my $worksheet = $ss->worksheet({title => 'Sheet1'}); # update cell by batch request $worksheet->batchupdate_cell( {col => 1, row => 1, input_value => 'name'}, {col => 2, row => 1, input_value => 'nick'}, {col => 3, row => 1, input_value => 'mail'}, {col => 4, row => 1, input_value => 'age'}, ); # get a cell object my $cell = $worksheet->cell({col => 1, row => 1}); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # get rows my @rows = $worksheet->rows; # search rows @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); =head1 METHODS =head2 rows(\%condition) Returns a list of Net::Google::Spreadsheets::Row objects. Acceptable arguments are: =over 4 =item sq Structured query on the full text in the worksheet. see the URL below for detail. =item orderby Set column name to use for ordering. =item reverse Set 'true' or 'false'. The default is 'false'. =back -See L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html#ListParameters> for details. +See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#ListParameters> for details. =head2 row(\%condition) Returns first item of spreadsheets(\%condition) if available. =head2 cells(\%args) Returns a list of Net::Google::Spreadsheets::Cell objects. Acceptable arguments are: =over 4 =item min-row =item max-row =item min-col =item max-col =item range =item return-empty =back -See L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html#CellParameters> for details. +See L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html#CellParameters> for details. =head2 cell(\%args) Returns Net::Google::Spreadsheets::Cell object. Arguments are: =over 4 =item col =item row =back =head2 batchupdate_cell(@args) update multiple cells with a batch request. Pass a list of hash references containing: =over 4 =item col =item row =item input_value =back =head1 SEE ALSO -L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> +L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> -L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> +L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/xt/04_synopsis.t b/xt/04_synopsis.t new file mode 100644 index 0000000..d414066 --- /dev/null +++ b/xt/04_synopsis.t @@ -0,0 +1,4 @@ +use Test::More; +eval "use Test::Synopsis"; +plan skip_all => "Test::Synopsis required for testing" if $@; +all_synopsis_ok();
lopnor/Net-Google-Spreadsheets
1fe663a4636c9824234c8849e88644be089a3d5f
better error message, default insertion mode to overwrite
diff --git a/lib/Net/Google/Spreadsheets/Table.pm b/lib/Net/Google/Spreadsheets/Table.pm index f1f31f5..3d85272 100644 --- a/lib/Net/Google/Spreadsheets/Table.pm +++ b/lib/Net/Google/Spreadsheets/Table.pm @@ -1,230 +1,230 @@ package Net::Google::Spreadsheets::Table; use Moose; use Moose::Util::TypeConstraints; use namespace::clean -except => 'meta'; use XML::Atom::Util qw(nodelist first create_element); subtype 'ColumnList' => as 'ArrayRef[Net::Google::Spreadsheets::Column]'; coerce 'ColumnList' => from 'ArrayRef[HashRef]' => via { [ map {Net::Google::Spreadsheets::Column->new($_)} @$_ ] }; coerce 'ColumnList' => from 'ArrayRef[Str]' => via { my @c; my $index = 0; for my $value (@$_) { push @c, Net::Google::Spreadsheets::Column->new( index => ++$index, name => $value, ); } \@c; }; coerce 'ColumnList' => from 'HashRef' => via { my @c; while (my ($key, $value) = each(%$_)) { push @c, Net::Google::Spreadsheets::Column->new( index => $key, name => $value, ); } \@c; }; subtype 'WorksheetName' => as 'Str'; coerce 'WorksheetName' => from 'Net::Google::Spreadsheets::Worksheet' => via { $_->title }; extends 'Net::Google::Spreadsheets::Base'; has record_feed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'ro', isa => 'Str', entry_class => 'Net::Google::Spreadsheets::Record', entry_arg_builder => sub { my ($self, $args) = @_; return {content => $args}; }, from_atom => sub { my $self = shift; $self->{record_feed} = first($self->elem, '', 'content')->getAttribute('src'); }, ); has summary => ( is => 'rw', isa => 'Str' ); has worksheet => ( is => 'ro', isa => 'WorksheetName', coerce => 1 ); has header => ( is => 'ro', isa => 'Int', required => 1, default => 1 ); has start_row => ( is => 'ro', isa => 'Int', required => 1, default => 2 ); has num_rows => ( is => 'ro', isa => 'Int' ); has columns => ( is => 'ro', isa => 'ColumnList', coerce => 1 ); -has insertion_mode => ( is => 'ro', isa => (enum ['insert', 'overwrite']), default => 'insert' ); +has insertion_mode => ( is => 'ro', isa => (enum ['insert', 'overwrite']), default => 'overwrite' ); after from_atom => sub { my ($self) = @_; my $gsns = $self->gsns->{uri}; my $elem = $self->elem; $self->{summary} = $self->atom->summary; $self->{worksheet} = first( $elem, $gsns, 'worksheet')->getAttribute('name'); $self->{header} = first( $elem, $gsns, 'header')->getAttribute('row'); my @columns; my $data = first($elem, $gsns, 'data'); $self->{insertion_mode} = $data->getAttribute('insertionMode'); $self->{start_row} = $data->getAttribute('startRow'); $self->{num_rows} = $data->getAttribute('numRows'); for (nodelist($data, $gsns, 'column')) { push @columns, Net::Google::Spreadsheets::Column->new( index => $_->getAttribute('index'), name => $_->getAttribute('name'), ); } $self->{columns} = \@columns; }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->summary($self->summary) if $self->summary; $entry->set($self->gsns, 'worksheet', '', {name => $self->worksheet}); $entry->set($self->gsns, 'header', '', {row => $self->header}); my $data = create_element($self->gsns, 'data'); $data->setAttribute(startRow => $self->start_row); $data->setAttribute(insertionMode => $self->insertion_mode); $data->setAttribute(startRow => $self->start_row) if $self->start_row; for ( @{$self->columns} ) { my $column = create_element($self->gsns, 'column'); $column->setAttribute(index => $_->index); $column->setAttribute(name => $_->name); $data->appendChild($column); } $entry->set($self->gsns, 'data', $data); return $entry; }; __PACKAGE__->meta->make_immutable; package # hide from PAUSE Net::Google::Spreadsheets::Column; use Moose; has 'index' => ( is => 'ro', isa => 'Str' ); has 'name' => ( is => 'ro', isa => 'Str' ); __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Table - A representation class for Google Spreadsheet table. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a row my $row = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->row( { sq => 'id = 1000' } ); # get the content of a row my $hashref = $row->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $row->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $row->param('name'); # returns 'Nobuo Danjou' my $newval = $row->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new row value (with all fields) my $hashref = $row->param; # same as $row->content; =head1 METHODS =head2 param sets and gets content value. =head1 CAVEATS Space characters in hash key of rows will be removed when you access rows. See below. my $ws = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'})->worksheet(1); $ws->batchupdate_cell( {col => 1,row => 1, input_value => 'name'}, {col => 2,row => 1, input_value => 'mail address'}, ); $ws->add_row( { name => 'my name', mailaddress => '[email protected]', # above passes, below fails. # 'mail address' => '[email protected]', } ); =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/UserAgent.pm b/lib/Net/Google/Spreadsheets/UserAgent.pm index 944a7b3..7d0d84c 100644 --- a/lib/Net/Google/Spreadsheets/UserAgent.pm +++ b/lib/Net/Google/Spreadsheets/UserAgent.pm @@ -1,148 +1,147 @@ package Net::Google::Spreadsheets::UserAgent; use Moose; use namespace::clean -except => 'meta'; use Carp; use LWP::UserAgent; use HTTP::Headers; use HTTP::Request; use URI; use XML::Atom::Entry; use XML::Atom::Feed; has source => ( isa => 'Str', is => 'ro', required => 1, ); has auth => ( isa => 'Str', is => 'rw', required => 1, ); has ua => ( isa => 'LWP::UserAgent', is => 'ro', required => 1, lazy_build => 1, ); sub _build_ua { my $self = shift; my $ua = LWP::UserAgent->new( agent => $self->source, requests_redirectable => [], ); $ua->default_headers( HTTP::Headers->new( Authorization => sprintf('GoogleLogin auth=%s', $self->auth), GData_Version => '3.0', ) ); return $ua; } __PACKAGE__->meta->make_immutable; sub request { my ($self, $args) = @_; my $method = delete $args->{method}; $method ||= $args->{content} ? 'POST' : 'GET'; my $uri = URI->new($args->{'uri'}); $uri->query_form($args->{query}) if $args->{query}; my $req = HTTP::Request->new($method => "$uri"); $req->content($args->{content}) if $args->{content}; $req->header('Content-Type' => $args->{content_type}) if $args->{content_type}; if ($args->{header}) { while (my @pair = each %{$args->{header}}) { $req->header(@pair); } } my $res = eval {$self->ua->request($req)}; if ($@ || !$res->is_success) { - warn $res->content; - die sprintf("request for '%s' failed: %s", $uri, $@ || $res->status_line); + die sprintf("request for '%s' failed:\n\t%s\n\t%s\n\t", $uri, ($@ || $res->status_line), ($! || $res->content)); } my $type = $res->content_type; if ($res->content_length && $type !~ m{^application/atom\+xml}) { die sprintf("Content-Type of response for '%s' is not 'application/atom+xml': %s", $uri, $type); } if (my $res_obj = $args->{response_object}) { my $obj = eval {$res_obj->new(\($res->content))}; croak sprintf("response for '%s' is broken: %s", $uri, $@) if $@; return $obj; } return $res; } sub feed { my ($self, $url, $query) = @_; return $self->request( { uri => $url, query => $query || undef, response_object => 'XML::Atom::Feed', } ); } sub entry { my ($self, $url, $query) = @_; return $self->request( { uri => $url, query => $query || undef, response_object => 'XML::Atom::Entry', } ); } sub post { my ($self, $url, $entry, $header) = @_; return $self->request( { uri => $url, content => $entry->as_xml, header => $header || undef, content_type => 'application/atom+xml', response_object => ref $entry, } ); } sub put { my ($self, $args) = @_; return $self->request( { method => 'PUT', uri => $args->{self}->editurl, content => $args->{entry}->as_xml, header => {'If-Match' => $args->{self}->etag }, content_type => 'application/atom+xml', response_object => 'XML::Atom::Entry', } ); } 1; __END__ =head1 NAME Net::Google::Spreadsheets::UserAgent - UserAgent for Net::Google::Spreadsheets. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut
lopnor/Net-Google-Spreadsheets
83c5c75c37352f33b3fb2d9fa3db68cff7765426
num_rows, insertion_mode support
diff --git a/lib/Net/Google/Spreadsheets/Table.pm b/lib/Net/Google/Spreadsheets/Table.pm index 066acf3..f1f31f5 100644 --- a/lib/Net/Google/Spreadsheets/Table.pm +++ b/lib/Net/Google/Spreadsheets/Table.pm @@ -1,231 +1,230 @@ package Net::Google::Spreadsheets::Table; use Moose; use Moose::Util::TypeConstraints; use namespace::clean -except => 'meta'; use XML::Atom::Util qw(nodelist first create_element); subtype 'ColumnList' => as 'ArrayRef[Net::Google::Spreadsheets::Column]'; coerce 'ColumnList' => from 'ArrayRef[HashRef]' => via { [ map {Net::Google::Spreadsheets::Column->new($_)} @$_ ] }; coerce 'ColumnList' => from 'ArrayRef[Str]' => via { my @c; my $index = 0; for my $value (@$_) { push @c, Net::Google::Spreadsheets::Column->new( index => ++$index, name => $value, ); } \@c; }; coerce 'ColumnList' => from 'HashRef' => via { my @c; while (my ($key, $value) = each(%$_)) { push @c, Net::Google::Spreadsheets::Column->new( index => $key, name => $value, ); } \@c; }; subtype 'WorksheetName' => as 'Str'; coerce 'WorksheetName' => from 'Net::Google::Spreadsheets::Worksheet' => via { $_->title }; extends 'Net::Google::Spreadsheets::Base'; has record_feed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'ro', isa => 'Str', entry_class => 'Net::Google::Spreadsheets::Record', entry_arg_builder => sub { my ($self, $args) = @_; return {content => $args}; }, from_atom => sub { my $self = shift; $self->{record_feed} = first($self->elem, '', 'content')->getAttribute('src'); }, ); has summary => ( is => 'rw', isa => 'Str' ); has worksheet => ( is => 'ro', isa => 'WorksheetName', coerce => 1 ); has header => ( is => 'ro', isa => 'Int', required => 1, default => 1 ); has start_row => ( is => 'ro', isa => 'Int', required => 1, default => 2 ); has num_rows => ( is => 'ro', isa => 'Int' ); has columns => ( is => 'ro', isa => 'ColumnList', coerce => 1 ); -has insertion_mode => ( is => 'ro', isa => 'Str', default => 'insert' ); +has insertion_mode => ( is => 'ro', isa => (enum ['insert', 'overwrite']), default => 'insert' ); after from_atom => sub { my ($self) = @_; my $gsns = $self->gsns->{uri}; my $elem = $self->elem; $self->{summary} = $self->atom->summary; $self->{worksheet} = first( $elem, $gsns, 'worksheet')->getAttribute('name'); $self->{header} = first( $elem, $gsns, 'header')->getAttribute('row'); my @columns; my $data = first($elem, $gsns, 'data'); $self->{insertion_mode} = $data->getAttribute('insertionMode'); $self->{start_row} = $data->getAttribute('startRow'); $self->{num_rows} = $data->getAttribute('numRows'); for (nodelist($data, $gsns, 'column')) { push @columns, Net::Google::Spreadsheets::Column->new( index => $_->getAttribute('index'), name => $_->getAttribute('name'), ); } $self->{columns} = \@columns; }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->summary($self->summary) if $self->summary; $entry->set($self->gsns, 'worksheet', '', {name => $self->worksheet}); $entry->set($self->gsns, 'header', '', {row => $self->header}); my $data = create_element($self->gsns, 'data'); $data->setAttribute(startRow => $self->start_row); $data->setAttribute(insertionMode => $self->insertion_mode); $data->setAttribute(startRow => $self->start_row) if $self->start_row; for ( @{$self->columns} ) { my $column = create_element($self->gsns, 'column'); $column->setAttribute(index => $_->index); $column->setAttribute(name => $_->name); $data->appendChild($column); } $entry->set($self->gsns, 'data', $data); - return $entry; }; __PACKAGE__->meta->make_immutable; package # hide from PAUSE Net::Google::Spreadsheets::Column; use Moose; has 'index' => ( is => 'ro', isa => 'Str' ); has 'name' => ( is => 'ro', isa => 'Str' ); __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Table - A representation class for Google Spreadsheet table. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a row my $row = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->row( { sq => 'id = 1000' } ); # get the content of a row my $hashref = $row->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $row->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $row->param('name'); # returns 'Nobuo Danjou' my $newval = $row->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new row value (with all fields) my $hashref = $row->param; # same as $row->content; =head1 METHODS =head2 param sets and gets content value. =head1 CAVEATS Space characters in hash key of rows will be removed when you access rows. See below. my $ws = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'})->worksheet(1); $ws->batchupdate_cell( {col => 1,row => 1, input_value => 'name'}, {col => 2,row => 1, input_value => 'mail address'}, ); $ws->add_row( { name => 'my name', mailaddress => '[email protected]', # above passes, below fails. # 'mail address' => '[email protected]', } ); =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/UserAgent.pm b/lib/Net/Google/Spreadsheets/UserAgent.pm index 61fc0df..944a7b3 100644 --- a/lib/Net/Google/Spreadsheets/UserAgent.pm +++ b/lib/Net/Google/Spreadsheets/UserAgent.pm @@ -1,147 +1,148 @@ package Net::Google::Spreadsheets::UserAgent; use Moose; use namespace::clean -except => 'meta'; use Carp; use LWP::UserAgent; use HTTP::Headers; use HTTP::Request; use URI; use XML::Atom::Entry; use XML::Atom::Feed; has source => ( isa => 'Str', is => 'ro', required => 1, ); has auth => ( isa => 'Str', is => 'rw', required => 1, ); has ua => ( isa => 'LWP::UserAgent', is => 'ro', required => 1, lazy_build => 1, ); sub _build_ua { my $self = shift; my $ua = LWP::UserAgent->new( agent => $self->source, requests_redirectable => [], ); $ua->default_headers( HTTP::Headers->new( Authorization => sprintf('GoogleLogin auth=%s', $self->auth), GData_Version => '3.0', ) ); return $ua; } __PACKAGE__->meta->make_immutable; sub request { my ($self, $args) = @_; my $method = delete $args->{method}; $method ||= $args->{content} ? 'POST' : 'GET'; my $uri = URI->new($args->{'uri'}); $uri->query_form($args->{query}) if $args->{query}; my $req = HTTP::Request->new($method => "$uri"); $req->content($args->{content}) if $args->{content}; $req->header('Content-Type' => $args->{content_type}) if $args->{content_type}; if ($args->{header}) { while (my @pair = each %{$args->{header}}) { $req->header(@pair); } } my $res = eval {$self->ua->request($req)}; if ($@ || !$res->is_success) { + warn $res->content; die sprintf("request for '%s' failed: %s", $uri, $@ || $res->status_line); } my $type = $res->content_type; if ($res->content_length && $type !~ m{^application/atom\+xml}) { die sprintf("Content-Type of response for '%s' is not 'application/atom+xml': %s", $uri, $type); } if (my $res_obj = $args->{response_object}) { my $obj = eval {$res_obj->new(\($res->content))}; croak sprintf("response for '%s' is broken: %s", $uri, $@) if $@; return $obj; } return $res; } sub feed { my ($self, $url, $query) = @_; return $self->request( { uri => $url, query => $query || undef, response_object => 'XML::Atom::Feed', } ); } sub entry { my ($self, $url, $query) = @_; return $self->request( { uri => $url, query => $query || undef, response_object => 'XML::Atom::Entry', } ); } sub post { my ($self, $url, $entry, $header) = @_; return $self->request( { uri => $url, content => $entry->as_xml, header => $header || undef, content_type => 'application/atom+xml', response_object => ref $entry, } ); } sub put { my ($self, $args) = @_; return $self->request( { method => 'PUT', uri => $args->{self}->editurl, content => $args->{entry}->as_xml, header => {'If-Match' => $args->{self}->etag }, content_type => 'application/atom+xml', response_object => 'XML::Atom::Entry', } ); } 1; __END__ =head1 NAME Net::Google::Spreadsheets::UserAgent - UserAgent for Net::Google::Spreadsheets. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/t/06_table.t b/t/06_table.t index c328968..4029efd 100644 --- a/t/06_table.t +++ b/t/06_table.t @@ -1,63 +1,103 @@ use t::Util; use Test::More; my $ws_title = 'test worksheet for table '.scalar localtime; my $table_title = 'test table '.scalar localtime; my $ss = spreadsheet; ok my $ws = $ss->add_worksheet({title => $ws_title}), 'add worksheet'; is $ws->title, $ws_title; my @t = $ss->tables; my $previous_table_count = scalar @t; { ok my $table = $ss->add_table( { title => $table_title, summary => 'this is summary of this table', worksheet => $ws, header => 1, start_row => 2, columns => [ {index => 1, name => 'name'}, {index => 2, name => 'mail address'}, {index => 3, name => 'nick'}, ], } ); isa_ok $table, 'Net::Google::Spreadsheets::Table'; } { my @t = $ss->tables; ok scalar @t; is scalar @t, $previous_table_count + 1; isa_ok $t[0], 'Net::Google::Spreadsheets::Table'; } { ok my $t = $ss->table({title => $table_title}); isa_ok $t, 'Net::Google::Spreadsheets::Table'; is $t->title, $table_title; is $t->summary, 'this is summary of this table'; is $t->worksheet, $ws->title; is $t->header, 1; is $t->start_row, 2; is scalar @{$t->columns}, 3; ok grep {$_->name eq 'name' && $_->index eq 'A'} @{$t->columns}; ok grep {$_->name eq 'mail address' && $_->index eq 'B'} @{$t->columns}; ok grep {$_->name eq 'nick' && $_->index eq 'C'} @{$t->columns}; } { ok my $t = $ss->table; isa_ok $t, 'Net::Google::Spreadsheets::Table'; ok $t->delete; my @t = $ss->tables; is scalar @t, $previous_table_count; } - ok $ws->delete, 'delete worksheet'; +for my $mode (qw(overwrite insert)) { + ok my $ws2 = $ss->add_worksheet( + { + title => 'insertion mode test '.scalar localtime, + col_count => 3, + row_count => 3, + } + ), 'add worksheet'; + ok $ss->add_table( + { + title => 'foobarbaz', + worksheet => $ws2, + insertion_mode => $mode, + start_row => 3, + columns => ['foo', 'bar', 'baz'], + } + ); + ok my $t = $ss->table({title => 'foobarbaz', worksheet => $ws2->title}); + isa_ok $t, 'Net::Google::Spreadsheets::Table'; + is $t->title, 'foobarbaz', 'table title'; + is $t->worksheet, $ws2->title, 'worksheet name'; + is $t->insertion_mode, $mode, 'insertion mode'; + is $t->start_row, 3, 'start row'; + my @c = @{$t->columns}; + is scalar @c, 3, 'column count is 3'; + ok grep({$_->name eq 'foo' && $_->index eq 'A'} @c), 'column foo exists'; + ok grep({$_->name eq 'bar' && $_->index eq 'B'} @c), 'column bar exists'; + ok grep({$_->name eq 'baz' && $_->index eq 'C'} @c), 'column baz exists'; + for my $i (1 .. 3) { + ok $t->add_record( + { + foo => 1, + bar => 2, + baz => 3, + } + ); + is $t->num_rows, $i; + } + ok $ws2->delete; +} + done_testing;
lopnor/Net-Google-Spreadsheets
b3e574c4adf4ceb961368155e4edb528fbf3debf
rename
diff --git a/MANIFEST b/MANIFEST index c3af096..afd0080 100644 --- a/MANIFEST +++ b/MANIFEST @@ -1,47 +1,50 @@ Changes inc/Module/Install.pm inc/Module/Install/AuthorTests.pm inc/Module/Install/Base.pm inc/Module/Install/Can.pm inc/Module/Install/Fetch.pm inc/Module/Install/Include.pm inc/Module/Install/Makefile.pm inc/Module/Install/Metadata.pm inc/Module/Install/TestBase.pm inc/Module/Install/Win32.pm inc/Module/Install/WriteAll.pm inc/Spiffy.pm inc/Test/Base.pm inc/Test/Base/Filter.pm inc/Test/Builder.pm inc/Test/Builder/Module.pm inc/Test/Exception.pm inc/Test/MockModule.pm inc/Test/MockObject.pm inc/Test/More.pm lib/Net/Google/Spreadsheets.pm lib/Net/Google/Spreadsheets/Base.pm lib/Net/Google/Spreadsheets/Cell.pm +lib/Net/Google/Spreadsheets/Record.pm +lib/Net/Google/Spreadsheets/Role/HasContent.pm lib/Net/Google/Spreadsheets/Row.pm lib/Net/Google/Spreadsheets/Spreadsheet.pm lib/Net/Google/Spreadsheets/Table.pm lib/Net/Google/Spreadsheets/Traits/Feed.pm lib/Net/Google/Spreadsheets/UserAgent.pm lib/Net/Google/Spreadsheets/Worksheet.pm Makefile.PL MANIFEST This list of files META.yml README t/00_compile.t t/01_instanciate.t -t/02_spreadsheets.t +t/02_spreadsheet.t t/03_worksheet.t t/04_cell.t -t/05_rows.t +t/05_row.t t/06_table.t +t/07_record.t t/08_error.t t/Util.pm xt/01_podspell.t xt/02_perlcritic.t xt/03_pod.t xt/perlcriticrc diff --git a/lib/Net/Google/Spreadsheets/Table.pm b/lib/Net/Google/Spreadsheets/Table.pm index 5e9ec0e..066acf3 100644 --- a/lib/Net/Google/Spreadsheets/Table.pm +++ b/lib/Net/Google/Spreadsheets/Table.pm @@ -1,231 +1,231 @@ package Net::Google::Spreadsheets::Table; use Moose; use Moose::Util::TypeConstraints; use namespace::clean -except => 'meta'; use XML::Atom::Util qw(nodelist first create_element); subtype 'ColumnList' => as 'ArrayRef[Net::Google::Spreadsheets::Column]'; coerce 'ColumnList' => from 'ArrayRef[HashRef]' => via { [ map {Net::Google::Spreadsheets::Column->new($_)} @$_ ] }; coerce 'ColumnList' => from 'ArrayRef[Str]' => via { my @c; my $index = 0; for my $value (@$_) { push @c, Net::Google::Spreadsheets::Column->new( index => ++$index, name => $value, ); } \@c; }; coerce 'ColumnList' => from 'HashRef' => via { my @c; while (my ($key, $value) = each(%$_)) { push @c, Net::Google::Spreadsheets::Column->new( index => $key, name => $value, ); } \@c; }; subtype 'WorksheetName' => as 'Str'; coerce 'WorksheetName' => from 'Net::Google::Spreadsheets::Worksheet' => via { $_->title }; extends 'Net::Google::Spreadsheets::Base'; has record_feed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'ro', isa => 'Str', entry_class => 'Net::Google::Spreadsheets::Record', entry_arg_builder => sub { my ($self, $args) = @_; return {content => $args}; }, from_atom => sub { my $self = shift; $self->{record_feed} = first($self->elem, '', 'content')->getAttribute('src'); }, ); has summary => ( is => 'rw', isa => 'Str' ); has worksheet => ( is => 'ro', isa => 'WorksheetName', coerce => 1 ); has header => ( is => 'ro', isa => 'Int', required => 1, default => 1 ); has start_row => ( is => 'ro', isa => 'Int', required => 1, default => 2 ); +has num_rows => ( is => 'ro', isa => 'Int' ); has columns => ( is => 'ro', isa => 'ColumnList', coerce => 1 ); +has insertion_mode => ( is => 'ro', isa => 'Str', default => 'insert' ); after from_atom => sub { my ($self) = @_; my $gsns = $self->gsns->{uri}; my $elem = $self->elem; $self->{summary} = $self->atom->summary; $self->{worksheet} = first( $elem, $gsns, 'worksheet')->getAttribute('name'); $self->{header} = first( $elem, $gsns, 'header')->getAttribute('row'); my @columns; my $data = first($elem, $gsns, 'data'); + $self->{insertion_mode} = $data->getAttribute('insertionMode'); + $self->{start_row} = $data->getAttribute('startRow'); + $self->{num_rows} = $data->getAttribute('numRows'); for (nodelist($data, $gsns, 'column')) { push @columns, Net::Google::Spreadsheets::Column->new( index => $_->getAttribute('index'), name => $_->getAttribute('name'), ); } $self->{columns} = \@columns; }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->summary($self->summary) if $self->summary; $entry->set($self->gsns, 'worksheet', '', {name => $self->worksheet}); $entry->set($self->gsns, 'header', '', {row => $self->header}); - my $columns = create_element($self->gsns, 'data'); - $columns->setAttribute(startRow => $self->start_row); + my $data = create_element($self->gsns, 'data'); + $data->setAttribute(startRow => $self->start_row); + $data->setAttribute(insertionMode => $self->insertion_mode); + $data->setAttribute(startRow => $self->start_row) if $self->start_row; for ( @{$self->columns} ) { my $column = create_element($self->gsns, 'column'); $column->setAttribute(index => $_->index); $column->setAttribute(name => $_->name); - $columns->appendChild($column); + $data->appendChild($column); } - $entry->set($self->gsns, 'data', $columns); + $entry->set($self->gsns, 'data', $data); return $entry; }; __PACKAGE__->meta->make_immutable; package # hide from PAUSE Net::Google::Spreadsheets::Column; use Moose; -has index => ( - is => 'ro', - isa => 'Str', -); - -has name => ( - is => 'ro', - isa => 'Str', -); +has 'index' => ( is => 'ro', isa => 'Str' ); +has 'name' => ( is => 'ro', isa => 'Str' ); __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Table - A representation class for Google Spreadsheet table. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a row my $row = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->row( { sq => 'id = 1000' } ); # get the content of a row my $hashref = $row->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $row->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $row->param('name'); # returns 'Nobuo Danjou' my $newval = $row->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new row value (with all fields) my $hashref = $row->param; # same as $row->content; =head1 METHODS =head2 param sets and gets content value. =head1 CAVEATS Space characters in hash key of rows will be removed when you access rows. See below. my $ws = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'})->worksheet(1); $ws->batchupdate_cell( {col => 1,row => 1, input_value => 'name'}, {col => 2,row => 1, input_value => 'mail address'}, ); $ws->add_row( { name => 'my name', mailaddress => '[email protected]', # above passes, below fails. # 'mail address' => '[email protected]', } ); =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/t/02_spreadsheets.t b/t/02_spreadsheet.t similarity index 100% rename from t/02_spreadsheets.t rename to t/02_spreadsheet.t diff --git a/t/05_rows.t b/t/05_row.t similarity index 100% rename from t/05_rows.t rename to t/05_row.t
lopnor/Net-Google-Spreadsheets
6f8ee92b997799d0f6348bc9cccdbc823f583afb
record support
diff --git a/lib/Net/Google/Spreadsheets/Base.pm b/lib/Net/Google/Spreadsheets/Base.pm index 557959f..e97fa42 100644 --- a/lib/Net/Google/Spreadsheets/Base.pm +++ b/lib/Net/Google/Spreadsheets/Base.pm @@ -1,147 +1,148 @@ package Net::Google::Spreadsheets::Base; use Moose; use namespace::clean -except => 'meta'; use Carp; has service => ( isa => 'Net::Google::Spreadsheets', is => 'ro', required => 1, lazy_build => 1, + weak_ref => 1, ); sub _build_service { shift->container->service }; my %ns = ( gd => 'http://schemas.google.com/g/2005', gs => 'http://schemas.google.com/spreadsheets/2006', gsx => 'http://schemas.google.com/spreadsheets/2006/extended', batch => 'http://schemas.google.com/gdata/batch', ); while (my ($prefix, $uri) = each %ns) { __PACKAGE__->meta->add_method( "${prefix}ns" => sub { XML::Atom::Namespace->new($prefix, $uri) } ); } my %rel2label = ( edit => 'editurl', self => 'selfurl', ); for (values %rel2label) { has $_ => (isa => 'Str', is => 'ro'); } has atom => ( isa => 'XML::Atom::Entry', is => 'rw', trigger => sub { my ($self, $arg) = @_; my $id = $self->atom->get($self->ns, 'id'); croak "can't set different id!" if $self->id && $self->id ne $id; $self->from_atom; }, handles => ['ns', 'elem', 'author'], ); has id => ( isa => 'Str', is => 'ro', ); has title => ( isa => 'Str', is => 'rw', default => 'untitled', trigger => sub {$_[0]->update} ); has etag => ( isa => 'Str', is => 'rw', ); has container => ( isa => 'Maybe[Net::Google::Spreadsheets::Base]', is => 'ro', ); __PACKAGE__->meta->make_immutable; sub from_atom { my ($self) = @_; $self->{title} = $self->atom->title; $self->{id} = $self->atom->get($self->ns, 'id'); $self->etag($self->elem->getAttributeNS($self->gdns->{uri}, 'etag')); for ($self->atom->link) { my $label = $rel2label{$_->rel} or next; $self->{$label} = $_->href; } } sub to_atom { my ($self) = @_; my $entry = XML::Atom::Entry->new; $entry->title($self->title) if $self->title; return $entry; } sub sync { my ($self) = @_; my $entry = $self->service->entry($self->selfurl); $self->atom($entry); } sub update { my ($self) = @_; $self->etag or return; my $atom = $self->service->put( { self => $self, entry => $self->to_atom, } ); $self->container->sync; $self->atom($atom); } sub delete { my $self = shift; my $res = $self->service->request( { uri => $self->editurl, method => 'DELETE', header => {'If-Match' => $self->etag}, } ); $self->container->sync if $res->is_success; return $res->is_success; } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Base - Base class of Net::Google::Spreadsheets::*. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Cell.pm b/lib/Net/Google/Spreadsheets/Cell.pm index 4f7c751..4a5fdcd 100644 --- a/lib/Net/Google/Spreadsheets/Cell.pm +++ b/lib/Net/Google/Spreadsheets/Cell.pm @@ -1,121 +1,122 @@ package Net::Google::Spreadsheets::Cell; use Moose; use namespace::clean -except => 'meta'; +use XML::Atom::Util qw(first); extends 'Net::Google::Spreadsheets::Base'; has content => ( isa => 'Str', is => 'ro', ); has row => ( isa => 'Int', is => 'ro', ); has col => ( isa => 'Int', is => 'ro', ); has input_value => ( isa => 'Str', is => 'rw', trigger => sub {$_[0]->update}, ); after from_atom => sub { my ($self) = @_; - my ($elem) = $self->elem->getElementsByTagNameNS($self->gsns->{uri}, 'cell'); + my $elem = first( $self->elem, $self->gsns->{uri}, 'cell'); $self->{row} = $elem->getAttribute('row'); $self->{col} = $elem->getAttribute('col'); $self->{input_value} = $elem->getAttribute('inputValue'); $self->{content} = $elem->textContent || ''; }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->gsns, 'cell', '', { row => $self->row, col => $self->col, inputValue => $self->input_value, } ); my $link = XML::Atom::Link->new; $link->rel('edit'); $link->type('application/atom+xml'); $link->href($self->editurl); $entry->link($link); $entry->id($self->id); return $entry; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Cell - A representation class for Google Spreadsheet cell. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a cell my $cell = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->cell( { col => 1, row => 1, } ); # update a cell $cell->input_value('new value'); # get the content of a cell my $value = $cell->content; =head1 ATTRIBUTES =head2 input_value Rewritable attribute. You can set formula like '=A1+B1' or so. =head2 content Read only attribute. You can get the result of formula. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Record.pm b/lib/Net/Google/Spreadsheets/Record.pm new file mode 100644 index 0000000..63ac0d5 --- /dev/null +++ b/lib/Net/Google/Spreadsheets/Record.pm @@ -0,0 +1,29 @@ +package Net::Google::Spreadsheets::Record; +use Moose; +use namespace::clean -except => 'meta'; +use XML::Atom::Util qw(nodelist); + +extends 'Net::Google::Spreadsheets::Base'; +with 'Net::Google::Spreadsheets::Role::HasContent'; + +after from_atom => sub { + my ($self) = @_; + for my $node (nodelist($self->elem, $self->gsns->{uri}, 'field')) { + $self->{content}->{$node->getAttribute('name')} = $node->textContent; + } +}; + +around to_atom => sub { + my ($next, $self) = @_; + my $entry = $next->($self); + while (my ($key, $value) = each %{$self->{content}}) { + $entry->add($self->gsns, 'field', $value, {name => $key}); + } + return $entry; +}; + +__PACKAGE__->meta->make_immutable; + +1; + +__END__ diff --git a/lib/Net/Google/Spreadsheets/Role/HasContent.pm b/lib/Net/Google/Spreadsheets/Role/HasContent.pm new file mode 100644 index 0000000..9b04bee --- /dev/null +++ b/lib/Net/Google/Spreadsheets/Role/HasContent.pm @@ -0,0 +1,27 @@ +package Net::Google::Spreadsheets::Role::HasContent; +use Moose::Role; +use namespace::clean -except => 'meta'; + +has content => ( + isa => 'HashRef', + is => 'rw', + default => sub { +{} }, + trigger => sub { $_[0]->update }, +); + +sub param { + my ($self, $arg) = @_; + return $self->content unless $arg; + if (ref $arg && (ref $arg eq 'HASH')) { + return $self->content( + { + %{$self->content}, + %$arg, + } + ); + } else { + return $self->content->{$arg}; + } +} + +1; diff --git a/lib/Net/Google/Spreadsheets/Row.pm b/lib/Net/Google/Spreadsheets/Row.pm index 00e0d6c..261781a 100644 --- a/lib/Net/Google/Spreadsheets/Row.pm +++ b/lib/Net/Google/Spreadsheets/Row.pm @@ -1,152 +1,147 @@ package Net::Google::Spreadsheets::Row; use Moose; use namespace::clean -except => 'meta'; +use XML::Atom::Util qw(nodelist); extends 'Net::Google::Spreadsheets::Base'; - -has content => ( - isa => 'HashRef', - is => 'rw', - default => sub { +{} }, - trigger => sub { $_[0]->update }, -); +with 'Net::Google::Spreadsheets::Role::HasContent'; after from_atom => sub { my ($self) = @_; - for my $node ($self->elem->getElementsByTagNameNS($self->gsxns->{uri}, '*')) { + for my $node (nodelist($self->elem, $self->gsxns->{uri}, '*')) { $self->{content}->{$node->localname} = $node->textContent; } }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->{content}}) { $entry->set($self->gsxns, $key, $value); } return $entry; }; __PACKAGE__->meta->make_immutable; sub param { my ($self, $arg) = @_; return $self->content unless $arg; if (ref $arg && (ref $arg eq 'HASH')) { return $self->content( { %{$self->content}, %$arg, } ); } else { return $self->content->{$arg}; } } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Row - A representation class for Google Spreadsheet row. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a row my $row = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->row( { sq => 'id = 1000' } ); # get the content of a row my $hashref = $row->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $row->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $row->param('name'); # returns 'Nobuo Danjou' my $newval = $row->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new row value (with all fields) my $hashref = $row->param; # same as $row->content; =head1 METHODS =head2 param sets and gets content value. =head1 CAVEATS Space characters in hash key of rows will be removed when you access rows. See below. my $ws = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'})->worksheet(1); $ws->batchupdate_cell( {col => 1,row => 1, input_value => 'name'}, {col => 2,row => 1, input_value => 'mail address'}, ); $ws->add_row( { name => 'my name', mailaddress => '[email protected]', # above passes, below fails. # 'mail address' => '[email protected]', } ); =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Table.pm b/lib/Net/Google/Spreadsheets/Table.pm index 178bad2..5e9ec0e 100644 --- a/lib/Net/Google/Spreadsheets/Table.pm +++ b/lib/Net/Google/Spreadsheets/Table.pm @@ -1,181 +1,231 @@ package Net::Google::Spreadsheets::Table; use Moose; use Moose::Util::TypeConstraints; - -use XML::Atom::Util; use namespace::clean -except => 'meta'; +use XML::Atom::Util qw(nodelist first create_element); subtype 'ColumnList' => as 'ArrayRef[Net::Google::Spreadsheets::Column]'; coerce 'ColumnList' => from 'ArrayRef[HashRef]' => via { - [ map {Net::Google::Spreadsheets::Column->new($_)} @$_ ]; + [ map {Net::Google::Spreadsheets::Column->new($_)} @$_ ] + }; +coerce 'ColumnList' + => from 'ArrayRef[Str]' + => via { + my @c; + my $index = 0; + for my $value (@$_) { + push @c, Net::Google::Spreadsheets::Column->new( + index => ++$index, + name => $value, + ); + } + \@c; + }; +coerce 'ColumnList' + => from 'HashRef' + => via { + my @c; + while (my ($key, $value) = each(%$_)) { + push @c, Net::Google::Spreadsheets::Column->new( + index => $key, + name => $value, + ); + } + \@c; }; subtype 'WorksheetName' => as 'Str'; coerce 'WorksheetName' => from 'Net::Google::Spreadsheets::Worksheet' => via { $_->title }; extends 'Net::Google::Spreadsheets::Base'; +has record_feed => ( + traits => ['Net::Google::Spreadsheets::Traits::Feed'], + is => 'ro', + isa => 'Str', + entry_class => 'Net::Google::Spreadsheets::Record', + entry_arg_builder => sub { + my ($self, $args) = @_; + return {content => $args}; + }, + from_atom => sub { + my $self = shift; + $self->{record_feed} = first($self->elem, '', 'content')->getAttribute('src'); + }, +); + has summary => ( is => 'rw', isa => 'Str' ); has worksheet => ( is => 'ro', isa => 'WorksheetName', coerce => 1 ); has header => ( is => 'ro', isa => 'Int', required => 1, default => 1 ); has start_row => ( is => 'ro', isa => 'Int', required => 1, default => 2 ); has columns => ( is => 'ro', isa => 'ColumnList', coerce => 1 ); after from_atom => sub { my ($self) = @_; + my $gsns = $self->gsns->{uri}; + my $elem = $self->elem; $self->{summary} = $self->atom->summary; - my ($ws) = $self->elem->getElementsByTagNameNS($self->gsns->{uri}, 'worksheet'); - $self->{worksheet} = $ws->getAttribute('name'); + $self->{worksheet} = first( $elem, $gsns, 'worksheet')->getAttribute('name'); + $self->{header} = first( $elem, $gsns, 'header')->getAttribute('row'); + my @columns; + my $data = first($elem, $gsns, 'data'); + for (nodelist($data, $gsns, 'column')) { + push @columns, Net::Google::Spreadsheets::Column->new( + index => $_->getAttribute('index'), + name => $_->getAttribute('name'), + ); + } + $self->{columns} = \@columns; }; around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->summary($self->summary) if $self->summary; $entry->set($self->gsns, 'worksheet', '', {name => $self->worksheet}); $entry->set($self->gsns, 'header', '', {row => $self->header}); - my $columns = XML::Atom::Util::create_element($self->gsns, 'data'); + my $columns = create_element($self->gsns, 'data'); $columns->setAttribute(startRow => $self->start_row); for ( @{$self->columns} ) { - my $column = XML::Atom::Util::create_element($self->gsns, 'column'); + my $column = create_element($self->gsns, 'column'); $column->setAttribute(index => $_->index); $column->setAttribute(name => $_->name); $columns->appendChild($column); } $entry->set($self->gsns, 'data', $columns); return $entry; }; __PACKAGE__->meta->make_immutable; package # hide from PAUSE Net::Google::Spreadsheets::Column; use Moose; has index => ( is => 'ro', - isa => 'Int', + isa => 'Str', ); has name => ( is => 'ro', isa => 'Str', ); __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Table - A representation class for Google Spreadsheet table. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a row my $row = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->row( { sq => 'id = 1000' } ); # get the content of a row my $hashref = $row->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $row->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $row->param('name'); # returns 'Nobuo Danjou' my $newval = $row->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new row value (with all fields) my $hashref = $row->param; # same as $row->content; =head1 METHODS =head2 param sets and gets content value. =head1 CAVEATS Space characters in hash key of rows will be removed when you access rows. See below. my $ws = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'})->worksheet(1); $ws->batchupdate_cell( {col => 1,row => 1, input_value => 'name'}, {col => 2,row => 1, input_value => 'mail address'}, ); $ws->add_row( { name => 'my name', mailaddress => '[email protected]', # above passes, below fails. # 'mail address' => '[email protected]', } ); =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Worksheet.pm b/lib/Net/Google/Spreadsheets/Worksheet.pm index d69bd53..56d3751 100644 --- a/lib/Net/Google/Spreadsheets/Worksheet.pm +++ b/lib/Net/Google/Spreadsheets/Worksheet.pm @@ -1,252 +1,254 @@ package Net::Google::Spreadsheets::Worksheet; use Moose; use Carp; use namespace::clean -except => 'meta'; extends 'Net::Google::Spreadsheets::Base'; use Net::Google::Spreadsheets::Cell; has row_feed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'ro', isa => 'Str', entry_class => 'Net::Google::Spreadsheets::Row', entry_arg_builder => sub { my ($self, $args) = @_; return {content => $args}; }, from_atom => sub { my $self = shift; $self->{row_feed} = $self->atom->content->elem->getAttribute('src'); }, ); has cellsfeed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'ro', isa => 'Str', entry_class => 'Net::Google::Spreadsheets::Cell', entry_arg_builder => sub { my ($self, $args) = @_; croak 'you can\'t call add_cell!'; }, query_arg_builder => sub { my ($self, $args) = @_; if (my $col = delete $args->{col}) { $args->{'max-col'} = $col; $args->{'min-col'} = $col; $args->{'return-empty'} = 'true'; } if (my $row = delete $args->{row}) { $args->{'max-row'} = $row; $args->{'min-row'} = $row; $args->{'return-empty'} = 'true'; } return $args; }, from_atom => sub { my ($self) = @_; ($self->{cellsfeed}) = map {$_->href} grep { $_->rel eq 'http://schemas.google.com/spreadsheets/2006#cellsfeed' } $self->atom->link; } ); has row_count => ( isa => 'Int', is => 'rw', default => 100, trigger => sub {$_[0]->update} ); has col_count => ( isa => 'Int', is => 'rw', default => 20, trigger => sub {$_[0]->update} ); around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->gsns, 'rowCount', $self->row_count); $entry->set($self->gsns, 'colCount', $self->col_count); return $entry; }; after from_atom => sub { my ($self) = @_; $self->{row_count} = $self->atom->get($self->gsns, 'rowCount'); $self->{col_count} = $self->atom->get($self->gsns, 'colCount'); }; __PACKAGE__->meta->make_immutable; sub batchupdate_cell { my ($self, @args) = @_; my $feed = XML::Atom::Feed->new; for ( @args ) { my $id = sprintf("%s/R%sC%s",$self->cellsfeed, $_->{row}, $_->{col}); $_->{id} = $_->{editurl} = $id; my $entry = Net::Google::Spreadsheets::Cell->new($_)->to_atom; $entry->set($self->batchns, operation => '', {type => 'update'}); $entry->set($self->batchns, id => $id); $feed->add_entry($entry); } my $res_feed = $self->service->post($self->cellsfeed."/batch", $feed, {'If-Match' => '*'}); $self->sync; return map { Net::Google::Spreadsheets::Cell->new( atom => $_, container => $self, ) } grep { - my ($node) = $_->elem->getElementsByTagNameNS($self->batchns->{uri}, 'status'); + my $node = XML::Atom::Util::first( + $_->elem, $self->batchns->{uri}, 'status' + ); $node->getAttribute('code') == 200; } $res_feed->entries; } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Worksheet - Representation of worksheet. =head1 SYNOPSIS my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); my $ss = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); my $worksheet = $ss->worksheet({title => 'Sheet1'}); # update cell by batch request $worksheet->batchupdate_cell( {col => 1, row => 1, input_value => 'name'}, {col => 2, row => 1, input_value => 'nick'}, {col => 3, row => 1, input_value => 'mail'}, {col => 4, row => 1, input_value => 'age'}, ); # get a cell object my $cell = $worksheet->cell({col => 1, row => 1}); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # get rows my @rows = $worksheet->rows; # search rows @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); =head1 METHODS =head2 rows(\%condition) Returns a list of Net::Google::Spreadsheets::Row objects. Acceptable arguments are: =over 4 =item sq Structured query on the full text in the worksheet. see the URL below for detail. =item orderby Set column name to use for ordering. =item reverse Set 'true' or 'false'. The default is 'false'. =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html#ListParameters> for details. =head2 row(\%condition) Returns first item of spreadsheets(\%condition) if available. =head2 cells(\%args) Returns a list of Net::Google::Spreadsheets::Cell objects. Acceptable arguments are: =over 4 =item min-row =item max-row =item min-col =item max-col =item range =item return-empty =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html#CellParameters> for details. =head2 cell(\%args) Returns Net::Google::Spreadsheets::Cell object. Arguments are: =over 4 =item col =item row =back =head2 batchupdate_cell(@args) update multiple cells with a batch request. Pass a list of hash references containing: =over 4 =item col =item row =item input_value =back =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/t/06_table.t b/t/06_table.t index bbab957..c328968 100644 --- a/t/06_table.t +++ b/t/06_table.t @@ -1,49 +1,63 @@ use t::Util; use Test::More; my $ws_title = 'test worksheet for table '.scalar localtime; +my $table_title = 'test table '.scalar localtime; my $ss = spreadsheet; ok my $ws = $ss->add_worksheet({title => $ws_title}), 'add worksheet'; is $ws->title, $ws_title; -{ - my @t = $ss->tables; - is scalar @t, 0; - is $ss->table, undef; -} +my @t = $ss->tables; +my $previous_table_count = scalar @t; { ok my $table = $ss->add_table( { - title => 'test table '.scalar localtime, + title => $table_title, summary => 'this is summary of this table', worksheet => $ws, header => 1, start_row => 2, columns => [ {index => 1, name => 'name'}, {index => 2, name => 'mail address'}, {index => 3, name => 'nick'}, ], } ); isa_ok $table, 'Net::Google::Spreadsheets::Table'; } { my @t = $ss->tables; ok scalar @t; + is scalar @t, $previous_table_count + 1; isa_ok $t[0], 'Net::Google::Spreadsheets::Table'; } +{ + ok my $t = $ss->table({title => $table_title}); + isa_ok $t, 'Net::Google::Spreadsheets::Table'; + is $t->title, $table_title; + is $t->summary, 'this is summary of this table'; + is $t->worksheet, $ws->title; + is $t->header, 1; + is $t->start_row, 2; + is scalar @{$t->columns}, 3; + ok grep {$_->name eq 'name' && $_->index eq 'A'} @{$t->columns}; + ok grep {$_->name eq 'mail address' && $_->index eq 'B'} @{$t->columns}; + ok grep {$_->name eq 'nick' && $_->index eq 'C'} @{$t->columns}; +} + { ok my $t = $ss->table; isa_ok $t, 'Net::Google::Spreadsheets::Table'; ok $t->delete; - is $ss->table, undef; + my @t = $ss->tables; + is scalar @t, $previous_table_count; } ok $ws->delete, 'delete worksheet'; done_testing; diff --git a/t/07_record.t b/t/07_record.t new file mode 100644 index 0000000..24d732d --- /dev/null +++ b/t/07_record.t @@ -0,0 +1,70 @@ +use t::Util; +use Test::More; + +my $ws_title = 'test worksheet for record '.scalar localtime; +my $table_title = 'test table '.scalar localtime; +my $ss = spreadsheet; +ok my $ws = $ss->add_worksheet({title => $ws_title}), 'add worksheet'; +is $ws->title, $ws_title; + +ok my $table = $ss->add_table( + { + worksheet => $ws, + columns => [ + 'name', + 'mail address', + 'nick', + ] + } +); + +{ + my $value = { + name => 'Nobuo Danjou', + 'mail address' => '[email protected]', + nick => 'lopnor', + }; + ok my $record = $table->add_record($value); + isa_ok $record, 'Net::Google::Spreadsheets::Record'; + is_deeply $record->content, $value; + is_deeply $record->param, $value; + is $record->param('name'), $value->{name}; + my $newval = {name => '檀上伸郎'}; + is_deeply $record->param($newval), { + %$value, + %$newval, + }; + is_deeply $record->content,{ + %$value, + %$newval, + }; + { + ok my $r = $table->record({sq => '"mail address" = "[email protected]"'}); + isa_ok $r, 'Net::Google::Spreadsheets::Record'; + is $r->param('mail address'), $value->{'mail address'}; + } + + my $value2 = { + name => 'Kazuhiro Osawa', + nick => 'yappo', + 'mail address' => '', + }; + $record->content($value2); + is_deeply $record->content, $value2; + is scalar $table->records, 1; + ok $record->delete; + is scalar $table->records, 0; +} + +{ + $table->add_record( { name => $_ } ) for qw(danjou lopnor soffritto); + is scalar $table->records, 3; + ok my $record = $table->record({sq => 'name = "lopnor"'}); + isa_ok $record, 'Net::Google::Spreadsheets::Record'; + is_deeply $record->content, {name => 'lopnor', nick => '', 'mail address' => ''}; +} + + +ok $ws->delete, 'delete worksheet'; + +done_testing;
lopnor/Net-Google-Spreadsheets
aea2b1f3204336ff32fd2ac30769ab3e0598690d
renamed methods
diff --git a/lib/Net/Google/Spreadsheets/Base.pm b/lib/Net/Google/Spreadsheets/Base.pm index 39a842e..557959f 100644 --- a/lib/Net/Google/Spreadsheets/Base.pm +++ b/lib/Net/Google/Spreadsheets/Base.pm @@ -1,147 +1,147 @@ package Net::Google::Spreadsheets::Base; use Moose; use namespace::clean -except => 'meta'; use Carp; has service => ( isa => 'Net::Google::Spreadsheets', is => 'ro', required => 1, lazy_build => 1, ); sub _build_service { shift->container->service }; my %ns = ( gd => 'http://schemas.google.com/g/2005', gs => 'http://schemas.google.com/spreadsheets/2006', gsx => 'http://schemas.google.com/spreadsheets/2006/extended', batch => 'http://schemas.google.com/gdata/batch', ); while (my ($prefix, $uri) = each %ns) { __PACKAGE__->meta->add_method( "${prefix}ns" => sub { XML::Atom::Namespace->new($prefix, $uri) } ); } my %rel2label = ( edit => 'editurl', self => 'selfurl', ); for (values %rel2label) { has $_ => (isa => 'Str', is => 'ro'); } has atom => ( isa => 'XML::Atom::Entry', is => 'rw', trigger => sub { my ($self, $arg) = @_; my $id = $self->atom->get($self->ns, 'id'); croak "can't set different id!" if $self->id && $self->id ne $id; - $self->_update_atom; + $self->from_atom; }, handles => ['ns', 'elem', 'author'], ); has id => ( isa => 'Str', is => 'ro', ); has title => ( isa => 'Str', is => 'rw', default => 'untitled', trigger => sub {$_[0]->update} ); has etag => ( isa => 'Str', is => 'rw', ); has container => ( isa => 'Maybe[Net::Google::Spreadsheets::Base]', is => 'ro', ); __PACKAGE__->meta->make_immutable; -sub _update_atom { +sub from_atom { my ($self) = @_; $self->{title} = $self->atom->title; $self->{id} = $self->atom->get($self->ns, 'id'); $self->etag($self->elem->getAttributeNS($self->gdns->{uri}, 'etag')); for ($self->atom->link) { my $label = $rel2label{$_->rel} or next; $self->{$label} = $_->href; } } -sub entry { +sub to_atom { my ($self) = @_; my $entry = XML::Atom::Entry->new; $entry->title($self->title) if $self->title; return $entry; } sub sync { my ($self) = @_; my $entry = $self->service->entry($self->selfurl); $self->atom($entry); } sub update { my ($self) = @_; $self->etag or return; my $atom = $self->service->put( { self => $self, - entry => $self->entry, + entry => $self->to_atom, } ); $self->container->sync; $self->atom($atom); } sub delete { my $self = shift; my $res = $self->service->request( { uri => $self->editurl, method => 'DELETE', header => {'If-Match' => $self->etag}, } ); $self->container->sync if $res->is_success; return $res->is_success; } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Base - Base class of Net::Google::Spreadsheets::*. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Cell.pm b/lib/Net/Google/Spreadsheets/Cell.pm index 07cf78d..4f7c751 100644 --- a/lib/Net/Google/Spreadsheets/Cell.pm +++ b/lib/Net/Google/Spreadsheets/Cell.pm @@ -1,121 +1,121 @@ package Net::Google::Spreadsheets::Cell; use Moose; use namespace::clean -except => 'meta'; extends 'Net::Google::Spreadsheets::Base'; has content => ( isa => 'Str', is => 'ro', ); has row => ( isa => 'Int', is => 'ro', ); has col => ( isa => 'Int', is => 'ro', ); has input_value => ( isa => 'Str', is => 'rw', trigger => sub {$_[0]->update}, ); -after _update_atom => sub { +after from_atom => sub { my ($self) = @_; my ($elem) = $self->elem->getElementsByTagNameNS($self->gsns->{uri}, 'cell'); $self->{row} = $elem->getAttribute('row'); $self->{col} = $elem->getAttribute('col'); $self->{input_value} = $elem->getAttribute('inputValue'); $self->{content} = $elem->textContent || ''; }; -around entry => sub { +around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->gsns, 'cell', '', { row => $self->row, col => $self->col, inputValue => $self->input_value, } ); my $link = XML::Atom::Link->new; $link->rel('edit'); $link->type('application/atom+xml'); $link->href($self->editurl); $entry->link($link); $entry->id($self->id); return $entry; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Cell - A representation class for Google Spreadsheet cell. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a cell my $cell = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->cell( { col => 1, row => 1, } ); # update a cell $cell->input_value('new value'); # get the content of a cell my $value = $cell->content; =head1 ATTRIBUTES =head2 input_value Rewritable attribute. You can set formula like '=A1+B1' or so. =head2 content Read only attribute. You can get the result of formula. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Row.pm b/lib/Net/Google/Spreadsheets/Row.pm index 424866c..00e0d6c 100644 --- a/lib/Net/Google/Spreadsheets/Row.pm +++ b/lib/Net/Google/Spreadsheets/Row.pm @@ -1,152 +1,152 @@ package Net::Google::Spreadsheets::Row; use Moose; use namespace::clean -except => 'meta'; extends 'Net::Google::Spreadsheets::Base'; has content => ( isa => 'HashRef', is => 'rw', default => sub { +{} }, trigger => sub { $_[0]->update }, ); -after _update_atom => sub { +after from_atom => sub { my ($self) = @_; for my $node ($self->elem->getElementsByTagNameNS($self->gsxns->{uri}, '*')) { $self->{content}->{$node->localname} = $node->textContent; } }; -around entry => sub { +around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->{content}}) { $entry->set($self->gsxns, $key, $value); } return $entry; }; __PACKAGE__->meta->make_immutable; sub param { my ($self, $arg) = @_; return $self->content unless $arg; if (ref $arg && (ref $arg eq 'HASH')) { return $self->content( { %{$self->content}, %$arg, } ); } else { return $self->content->{$arg}; } } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Row - A representation class for Google Spreadsheet row. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a row my $row = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->row( { sq => 'id = 1000' } ); # get the content of a row my $hashref = $row->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $row->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $row->param('name'); # returns 'Nobuo Danjou' my $newval = $row->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new row value (with all fields) my $hashref = $row->param; # same as $row->content; =head1 METHODS =head2 param sets and gets content value. =head1 CAVEATS Space characters in hash key of rows will be removed when you access rows. See below. my $ws = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'})->worksheet(1); $ws->batchupdate_cell( {col => 1,row => 1, input_value => 'name'}, {col => 2,row => 1, input_value => 'mail address'}, ); $ws->add_row( { name => 'my name', mailaddress => '[email protected]', # above passes, below fails. # 'mail address' => '[email protected]', } ); =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Spreadsheet.pm b/lib/Net/Google/Spreadsheets/Spreadsheet.pm index 18e0558..3fb2886 100644 --- a/lib/Net/Google/Spreadsheets/Spreadsheet.pm +++ b/lib/Net/Google/Spreadsheets/Spreadsheet.pm @@ -1,119 +1,119 @@ package Net::Google::Spreadsheets::Spreadsheet; use Moose; use namespace::clean -except => 'meta'; extends 'Net::Google::Spreadsheets::Base'; use Net::Google::Spreadsheets::Worksheet; use Path::Class; use URI; has +title => ( is => 'ro', ); has key => ( isa => 'Str', is => 'ro', ); has worksheet_feed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'rw', isa => 'Str', entry_class => 'Net::Google::Spreadsheets::Worksheet', - _update_atom => sub { + from_atom => sub { my ($self) = @_; $self->{worksheet_feed} = $self->atom->content->elem->getAttribute('src'); }, ); has table_feed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'rw', isa => 'Str', entry_class => 'Net::Google::Spreadsheets::Table', lazy_build => 1, ); sub _build_table_feed { my $self = shift; return sprintf('http://spreadsheets.google.com/feeds/%s/tables',$self->key); } -after _update_atom => sub { +after from_atom => sub { my ($self) = @_; $self->{key} = file(URI->new($self->id)->path)->basename; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Spreadsheet - Representation of spreadsheet. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); =head1 METHODS =head2 worksheets(\%condition) Returns a list of Net::Google::Spreadsheets::Worksheet objects. Acceptable arguments are: =over 4 =item title =item title-exact =back =head2 worksheet(\%condition) Returns first item of worksheets(\%condition) if available. =head2 add_worksheet(\%attribuets) Creates new worksheet and returns a Net::Google::Spreadsheets::Worksheet object representing it. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Table.pm b/lib/Net/Google/Spreadsheets/Table.pm index 61c6e67..178bad2 100644 --- a/lib/Net/Google/Spreadsheets/Table.pm +++ b/lib/Net/Google/Spreadsheets/Table.pm @@ -1,181 +1,181 @@ package Net::Google::Spreadsheets::Table; use Moose; use Moose::Util::TypeConstraints; use XML::Atom::Util; use namespace::clean -except => 'meta'; subtype 'ColumnList' => as 'ArrayRef[Net::Google::Spreadsheets::Column]'; coerce 'ColumnList' => from 'ArrayRef[HashRef]' => via { [ map {Net::Google::Spreadsheets::Column->new($_)} @$_ ]; }; subtype 'WorksheetName' => as 'Str'; coerce 'WorksheetName' => from 'Net::Google::Spreadsheets::Worksheet' => via { $_->title }; extends 'Net::Google::Spreadsheets::Base'; has summary => ( is => 'rw', isa => 'Str' ); has worksheet => ( is => 'ro', isa => 'WorksheetName', coerce => 1 ); has header => ( is => 'ro', isa => 'Int', required => 1, default => 1 ); has start_row => ( is => 'ro', isa => 'Int', required => 1, default => 2 ); has columns => ( is => 'ro', isa => 'ColumnList', coerce => 1 ); -after _update_atom => sub { +after from_atom => sub { my ($self) = @_; - for my $node ($self->elem->getElementsByTagNameNS($self->gsxns->{uri}, '*')) { - $self->{content}->{$node->localname} = $node->textContent; - } + $self->{summary} = $self->atom->summary; + my ($ws) = $self->elem->getElementsByTagNameNS($self->gsns->{uri}, 'worksheet'); + $self->{worksheet} = $ws->getAttribute('name'); }; -around entry => sub { +around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->summary($self->summary) if $self->summary; $entry->set($self->gsns, 'worksheet', '', {name => $self->worksheet}); $entry->set($self->gsns, 'header', '', {row => $self->header}); my $columns = XML::Atom::Util::create_element($self->gsns, 'data'); $columns->setAttribute(startRow => $self->start_row); for ( @{$self->columns} ) { my $column = XML::Atom::Util::create_element($self->gsns, 'column'); $column->setAttribute(index => $_->index); $column->setAttribute(name => $_->name); $columns->appendChild($column); } $entry->set($self->gsns, 'data', $columns); return $entry; }; __PACKAGE__->meta->make_immutable; package # hide from PAUSE Net::Google::Spreadsheets::Column; use Moose; has index => ( is => 'ro', isa => 'Int', ); has name => ( is => 'ro', isa => 'Str', ); __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Table - A representation class for Google Spreadsheet table. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a row my $row = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->row( { sq => 'id = 1000' } ); # get the content of a row my $hashref = $row->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $row->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $row->param('name'); # returns 'Nobuo Danjou' my $newval = $row->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new row value (with all fields) my $hashref = $row->param; # same as $row->content; =head1 METHODS =head2 param sets and gets content value. =head1 CAVEATS Space characters in hash key of rows will be removed when you access rows. See below. my $ws = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'})->worksheet(1); $ws->batchupdate_cell( {col => 1,row => 1, input_value => 'name'}, {col => 2,row => 1, input_value => 'mail address'}, ); $ws->add_row( { name => 'my name', mailaddress => '[email protected]', # above passes, below fails. # 'mail address' => '[email protected]', } ); =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Traits/Feed.pm b/lib/Net/Google/Spreadsheets/Traits/Feed.pm index 3e223a2..ea015ff 100644 --- a/lib/Net/Google/Spreadsheets/Traits/Feed.pm +++ b/lib/Net/Google/Spreadsheets/Traits/Feed.pm @@ -1,101 +1,101 @@ package Net::Google::Spreadsheets::Traits::Feed; use Moose::Role; has entry_class => ( is => 'ro', isa => 'Str', required => 1, ); has entry_arg_builder => ( is => 'ro', isa => 'CodeRef', required => 1, default => sub { return sub { my ($self, $args) = @_; return $args || {}; }; }, ); has query_arg_builder => ( is => 'ro', isa => 'CodeRef', required => 1, default => sub { return sub { my ($self, $args) = @_; return $args || {}; }; }, ); -has _update_atom => ( +has from_atom => ( is => 'ro', isa => 'CodeRef', required => 1, default => sub { return sub {}; } ); after install_accessors => sub { my $attr = shift; my $class = $attr->associated_class; my $key = $attr->name; my $entry_class = $attr->entry_class; my $arg_builder = $attr->entry_arg_builder; my $query_builder = $attr->query_arg_builder; - my $_update_atom = $attr->_update_atom; + my $from_atom = $attr->from_atom; my $method_base = lc [ split('::', $entry_class) ]->[-1]; $class->add_method( "add_${method_base}" => sub { my ($self, $args) = @_; Class::MOP::load_class($entry_class); $args = $arg_builder->($self, $args); - my $entry = $entry_class->new($args)->entry; + my $entry = $entry_class->new($args)->to_atom; my $atom = $self->service->post($self->$key, $entry); $self->sync; return $entry_class->new( container => $self, atom => $atom, ); } ); $class->add_method( "${method_base}s" => sub { my ($self, $cond) = @_; $self->$key or return; Class::MOP::load_class($entry_class); $cond = $query_builder->($self, $cond); my $feed = $self->service->feed($self->$key, $cond); return map { $entry_class->new( container => $self, atom => $_, ) } $feed->entries; } ); $class->add_method( $method_base => sub { my ($self, $cond) = @_; my $method = "${method_base}s"; return [ $self->$method($cond) ]->[0]; } ); $class->add_after_method_modifier( - '_update_atom' => sub { + 'from_atom' => sub { my $self = shift; - $_update_atom->($self); + $from_atom->($self); } ); }; 1; diff --git a/lib/Net/Google/Spreadsheets/Worksheet.pm b/lib/Net/Google/Spreadsheets/Worksheet.pm index 30f37d7..d69bd53 100644 --- a/lib/Net/Google/Spreadsheets/Worksheet.pm +++ b/lib/Net/Google/Spreadsheets/Worksheet.pm @@ -1,252 +1,252 @@ package Net::Google::Spreadsheets::Worksheet; use Moose; use Carp; use namespace::clean -except => 'meta'; extends 'Net::Google::Spreadsheets::Base'; use Net::Google::Spreadsheets::Cell; has row_feed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'ro', isa => 'Str', entry_class => 'Net::Google::Spreadsheets::Row', entry_arg_builder => sub { my ($self, $args) = @_; return {content => $args}; }, - _update_atom => sub { + from_atom => sub { my $self = shift; $self->{row_feed} = $self->atom->content->elem->getAttribute('src'); }, ); has cellsfeed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'ro', isa => 'Str', entry_class => 'Net::Google::Spreadsheets::Cell', entry_arg_builder => sub { my ($self, $args) = @_; croak 'you can\'t call add_cell!'; }, query_arg_builder => sub { my ($self, $args) = @_; if (my $col = delete $args->{col}) { $args->{'max-col'} = $col; $args->{'min-col'} = $col; $args->{'return-empty'} = 'true'; } if (my $row = delete $args->{row}) { $args->{'max-row'} = $row; $args->{'min-row'} = $row; $args->{'return-empty'} = 'true'; } return $args; }, - _update_atom => sub { + from_atom => sub { my ($self) = @_; ($self->{cellsfeed}) = map {$_->href} grep { $_->rel eq 'http://schemas.google.com/spreadsheets/2006#cellsfeed' } $self->atom->link; } ); has row_count => ( isa => 'Int', is => 'rw', default => 100, trigger => sub {$_[0]->update} ); has col_count => ( isa => 'Int', is => 'rw', default => 20, trigger => sub {$_[0]->update} ); -around entry => sub { +around to_atom => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->gsns, 'rowCount', $self->row_count); $entry->set($self->gsns, 'colCount', $self->col_count); return $entry; }; -after _update_atom => sub { +after from_atom => sub { my ($self) = @_; $self->{row_count} = $self->atom->get($self->gsns, 'rowCount'); $self->{col_count} = $self->atom->get($self->gsns, 'colCount'); }; __PACKAGE__->meta->make_immutable; sub batchupdate_cell { my ($self, @args) = @_; my $feed = XML::Atom::Feed->new; for ( @args ) { my $id = sprintf("%s/R%sC%s",$self->cellsfeed, $_->{row}, $_->{col}); $_->{id} = $_->{editurl} = $id; - my $entry = Net::Google::Spreadsheets::Cell->new($_)->entry; + my $entry = Net::Google::Spreadsheets::Cell->new($_)->to_atom; $entry->set($self->batchns, operation => '', {type => 'update'}); $entry->set($self->batchns, id => $id); $feed->add_entry($entry); } my $res_feed = $self->service->post($self->cellsfeed."/batch", $feed, {'If-Match' => '*'}); $self->sync; return map { Net::Google::Spreadsheets::Cell->new( atom => $_, container => $self, ) } grep { my ($node) = $_->elem->getElementsByTagNameNS($self->batchns->{uri}, 'status'); $node->getAttribute('code') == 200; } $res_feed->entries; } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Worksheet - Representation of worksheet. =head1 SYNOPSIS my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); my $ss = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); my $worksheet = $ss->worksheet({title => 'Sheet1'}); # update cell by batch request $worksheet->batchupdate_cell( {col => 1, row => 1, input_value => 'name'}, {col => 2, row => 1, input_value => 'nick'}, {col => 3, row => 1, input_value => 'mail'}, {col => 4, row => 1, input_value => 'age'}, ); # get a cell object my $cell = $worksheet->cell({col => 1, row => 1}); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # get rows my @rows = $worksheet->rows; # search rows @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); =head1 METHODS =head2 rows(\%condition) Returns a list of Net::Google::Spreadsheets::Row objects. Acceptable arguments are: =over 4 =item sq Structured query on the full text in the worksheet. see the URL below for detail. =item orderby Set column name to use for ordering. =item reverse Set 'true' or 'false'. The default is 'false'. =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html#ListParameters> for details. =head2 row(\%condition) Returns first item of spreadsheets(\%condition) if available. =head2 cells(\%args) Returns a list of Net::Google::Spreadsheets::Cell objects. Acceptable arguments are: =over 4 =item min-row =item max-row =item min-col =item max-col =item range =item return-empty =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html#CellParameters> for details. =head2 cell(\%args) Returns Net::Google::Spreadsheets::Cell object. Arguments are: =over 4 =item col =item row =back =head2 batchupdate_cell(@args) update multiple cells with a batch request. Pass a list of hash references containing: =over 4 =item col =item row =item input_value =back =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut
lopnor/Net-Google-Spreadsheets
840fbe6301b0415eb110ea1e520f2cdaaccafa44
table creation
diff --git a/MANIFEST b/MANIFEST index 6dfffc9..c3af096 100644 --- a/MANIFEST +++ b/MANIFEST @@ -1,42 +1,47 @@ Changes inc/Module/Install.pm inc/Module/Install/AuthorTests.pm inc/Module/Install/Base.pm inc/Module/Install/Can.pm inc/Module/Install/Fetch.pm inc/Module/Install/Include.pm inc/Module/Install/Makefile.pm inc/Module/Install/Metadata.pm inc/Module/Install/TestBase.pm inc/Module/Install/Win32.pm inc/Module/Install/WriteAll.pm inc/Spiffy.pm inc/Test/Base.pm inc/Test/Base/Filter.pm inc/Test/Builder.pm inc/Test/Builder/Module.pm inc/Test/Exception.pm +inc/Test/MockModule.pm +inc/Test/MockObject.pm inc/Test/More.pm lib/Net/Google/Spreadsheets.pm lib/Net/Google/Spreadsheets/Base.pm lib/Net/Google/Spreadsheets/Cell.pm lib/Net/Google/Spreadsheets/Row.pm lib/Net/Google/Spreadsheets/Spreadsheet.pm +lib/Net/Google/Spreadsheets/Table.pm +lib/Net/Google/Spreadsheets/Traits/Feed.pm lib/Net/Google/Spreadsheets/UserAgent.pm lib/Net/Google/Spreadsheets/Worksheet.pm Makefile.PL MANIFEST This list of files META.yml README t/00_compile.t t/01_instanciate.t t/02_spreadsheets.t t/03_worksheet.t t/04_cell.t t/05_rows.t -t/06_error.t +t/06_table.t +t/08_error.t t/Util.pm xt/01_podspell.t xt/02_perlcritic.t xt/03_pod.t xt/perlcriticrc diff --git a/lib/Net/Google/Spreadsheets/Spreadsheet.pm b/lib/Net/Google/Spreadsheets/Spreadsheet.pm index 6d8eff5..18e0558 100644 --- a/lib/Net/Google/Spreadsheets/Spreadsheet.pm +++ b/lib/Net/Google/Spreadsheets/Spreadsheet.pm @@ -1,119 +1,119 @@ package Net::Google::Spreadsheets::Spreadsheet; use Moose; use namespace::clean -except => 'meta'; extends 'Net::Google::Spreadsheets::Base'; use Net::Google::Spreadsheets::Worksheet; use Path::Class; +use URI; has +title => ( is => 'ro', ); has key => ( isa => 'Str', is => 'ro', - required => 1, - lazy_build => 1, ); -sub _build_key { - my $self = shift; - my $key = file(URI->new($self->id)->path)->basename; - return $key; -} - has worksheet_feed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'rw', isa => 'Str', entry_class => 'Net::Google::Spreadsheets::Worksheet', _update_atom => sub { my ($self) = @_; $self->{worksheet_feed} = $self->atom->content->elem->getAttribute('src'); }, ); has table_feed => ( traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'rw', isa => 'Str', entry_class => 'Net::Google::Spreadsheets::Table', - default => sub { - my $self = shift; - return sprintf('http://spreadsheets.google.com/feeds/%s/tables',$self->key); - } + lazy_build => 1, ); +sub _build_table_feed { + my $self = shift; + return sprintf('http://spreadsheets.google.com/feeds/%s/tables',$self->key); +} + +after _update_atom => sub { + my ($self) = @_; + $self->{key} = file(URI->new($self->id)->path)->basename; +}; + __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Spreadsheet - Representation of spreadsheet. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); =head1 METHODS =head2 worksheets(\%condition) Returns a list of Net::Google::Spreadsheets::Worksheet objects. Acceptable arguments are: =over 4 =item title =item title-exact =back =head2 worksheet(\%condition) Returns first item of worksheets(\%condition) if available. =head2 add_worksheet(\%attribuets) Creates new worksheet and returns a Net::Google::Spreadsheets::Worksheet object representing it. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Table.pm b/lib/Net/Google/Spreadsheets/Table.pm index d25a9e6..61c6e67 100644 --- a/lib/Net/Google/Spreadsheets/Table.pm +++ b/lib/Net/Google/Spreadsheets/Table.pm @@ -1,130 +1,181 @@ package Net::Google::Spreadsheets::Table; use Moose; +use Moose::Util::TypeConstraints; + +use XML::Atom::Util; use namespace::clean -except => 'meta'; +subtype 'ColumnList' + => as 'ArrayRef[Net::Google::Spreadsheets::Column]'; +coerce 'ColumnList' + => from 'ArrayRef[HashRef]' + => via { + [ map {Net::Google::Spreadsheets::Column->new($_)} @$_ ]; + }; + +subtype 'WorksheetName' + => as 'Str'; +coerce 'WorksheetName' + => from 'Net::Google::Spreadsheets::Worksheet' + => via { + $_->title + }; + extends 'Net::Google::Spreadsheets::Base'; +has summary => ( is => 'rw', isa => 'Str' ); +has worksheet => ( is => 'ro', isa => 'WorksheetName', coerce => 1 ); +has header => ( is => 'ro', isa => 'Int', required => 1, default => 1 ); +has start_row => ( is => 'ro', isa => 'Int', required => 1, default => 2 ); +has columns => ( is => 'ro', isa => 'ColumnList', coerce => 1 ); + after _update_atom => sub { my ($self) = @_; for my $node ($self->elem->getElementsByTagNameNS($self->gsxns->{uri}, '*')) { $self->{content}->{$node->localname} = $node->textContent; } }; around entry => sub { my ($next, $self) = @_; my $entry = $next->($self); - while (my ($key, $value) = each %{$self->{content}}) { - $entry->set($self->gsxns, $key, $value); + $entry->summary($self->summary) if $self->summary; + $entry->set($self->gsns, 'worksheet', '', {name => $self->worksheet}); + $entry->set($self->gsns, 'header', '', {row => $self->header}); + my $columns = XML::Atom::Util::create_element($self->gsns, 'data'); + $columns->setAttribute(startRow => $self->start_row); + for ( @{$self->columns} ) { + my $column = XML::Atom::Util::create_element($self->gsns, 'column'); + $column->setAttribute(index => $_->index); + $column->setAttribute(name => $_->name); + $columns->appendChild($column); } + $entry->set($self->gsns, 'data', $columns); + return $entry; }; __PACKAGE__->meta->make_immutable; +package # hide from PAUSE + Net::Google::Spreadsheets::Column; +use Moose; + +has index => ( + is => 'ro', + isa => 'Int', +); + +has name => ( + is => 'ro', + isa => 'Str', +); + +__PACKAGE__->meta->make_immutable; + 1; __END__ =head1 NAME Net::Google::Spreadsheets::Table - A representation class for Google Spreadsheet table. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a row my $row = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->row( { sq => 'id = 1000' } ); # get the content of a row my $hashref = $row->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $row->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $row->param('name'); # returns 'Nobuo Danjou' my $newval = $row->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new row value (with all fields) my $hashref = $row->param; # same as $row->content; =head1 METHODS =head2 param sets and gets content value. =head1 CAVEATS Space characters in hash key of rows will be removed when you access rows. See below. my $ws = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'})->worksheet(1); $ws->batchupdate_cell( {col => 1,row => 1, input_value => 'name'}, {col => 2,row => 1, input_value => 'mail address'}, ); $ws->add_row( { name => 'my name', mailaddress => '[email protected]', # above passes, below fails. # 'mail address' => '[email protected]', } ); =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/UserAgent.pm b/lib/Net/Google/Spreadsheets/UserAgent.pm index ba95962..61fc0df 100644 --- a/lib/Net/Google/Spreadsheets/UserAgent.pm +++ b/lib/Net/Google/Spreadsheets/UserAgent.pm @@ -1,147 +1,147 @@ package Net::Google::Spreadsheets::UserAgent; use Moose; use namespace::clean -except => 'meta'; use Carp; use LWP::UserAgent; use HTTP::Headers; use HTTP::Request; use URI; use XML::Atom::Entry; use XML::Atom::Feed; has source => ( isa => 'Str', is => 'ro', required => 1, ); has auth => ( isa => 'Str', is => 'rw', required => 1, ); has ua => ( isa => 'LWP::UserAgent', is => 'ro', required => 1, lazy_build => 1, ); sub _build_ua { my $self = shift; my $ua = LWP::UserAgent->new( agent => $self->source, requests_redirectable => [], ); $ua->default_headers( HTTP::Headers->new( Authorization => sprintf('GoogleLogin auth=%s', $self->auth), - GData_Version => 2, + GData_Version => '3.0', ) ); return $ua; } __PACKAGE__->meta->make_immutable; sub request { my ($self, $args) = @_; my $method = delete $args->{method}; $method ||= $args->{content} ? 'POST' : 'GET'; my $uri = URI->new($args->{'uri'}); $uri->query_form($args->{query}) if $args->{query}; my $req = HTTP::Request->new($method => "$uri"); $req->content($args->{content}) if $args->{content}; $req->header('Content-Type' => $args->{content_type}) if $args->{content_type}; if ($args->{header}) { while (my @pair = each %{$args->{header}}) { $req->header(@pair); } } my $res = eval {$self->ua->request($req)}; if ($@ || !$res->is_success) { die sprintf("request for '%s' failed: %s", $uri, $@ || $res->status_line); } my $type = $res->content_type; if ($res->content_length && $type !~ m{^application/atom\+xml}) { die sprintf("Content-Type of response for '%s' is not 'application/atom+xml': %s", $uri, $type); } if (my $res_obj = $args->{response_object}) { my $obj = eval {$res_obj->new(\($res->content))}; croak sprintf("response for '%s' is broken: %s", $uri, $@) if $@; return $obj; } return $res; } sub feed { my ($self, $url, $query) = @_; return $self->request( { uri => $url, query => $query || undef, response_object => 'XML::Atom::Feed', } ); } sub entry { my ($self, $url, $query) = @_; return $self->request( { uri => $url, query => $query || undef, response_object => 'XML::Atom::Entry', } ); } sub post { my ($self, $url, $entry, $header) = @_; return $self->request( { uri => $url, content => $entry->as_xml, header => $header || undef, content_type => 'application/atom+xml', response_object => ref $entry, } ); } sub put { my ($self, $args) = @_; return $self->request( { method => 'PUT', uri => $args->{self}->editurl, content => $args->{entry}->as_xml, header => {'If-Match' => $args->{self}->etag }, content_type => 'application/atom+xml', response_object => 'XML::Atom::Entry', } ); } 1; __END__ =head1 NAME Net::Google::Spreadsheets::UserAgent - UserAgent for Net::Google::Spreadsheets. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/t/06_table.t b/t/06_table.t new file mode 100644 index 0000000..bbab957 --- /dev/null +++ b/t/06_table.t @@ -0,0 +1,49 @@ +use t::Util; +use Test::More; + +my $ws_title = 'test worksheet for table '.scalar localtime; +my $ss = spreadsheet; +ok my $ws = $ss->add_worksheet({title => $ws_title}), 'add worksheet'; +is $ws->title, $ws_title; + +{ + my @t = $ss->tables; + is scalar @t, 0; + is $ss->table, undef; +} + +{ + ok my $table = $ss->add_table( + { + title => 'test table '.scalar localtime, + summary => 'this is summary of this table', + worksheet => $ws, + header => 1, + start_row => 2, + columns => [ + {index => 1, name => 'name'}, + {index => 2, name => 'mail address'}, + {index => 3, name => 'nick'}, + ], + } + ); + isa_ok $table, 'Net::Google::Spreadsheets::Table'; +} + +{ + my @t = $ss->tables; + ok scalar @t; + isa_ok $t[0], 'Net::Google::Spreadsheets::Table'; +} + +{ + ok my $t = $ss->table; + isa_ok $t, 'Net::Google::Spreadsheets::Table'; + + ok $t->delete; + is $ss->table, undef; +} + +ok $ws->delete, 'delete worksheet'; + +done_testing; diff --git a/t/06_error.t b/t/08_error.t similarity index 100% rename from t/06_error.t rename to t/08_error.t
lopnor/Net-Google-Spreadsheets
1dc0ff2c31805679ac653fc3408b880add8011a0
feed accessor with taints
diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index d442e43..e36c031 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,307 +1,276 @@ package Net::Google::Spreadsheets; use Moose; use namespace::clean -except => 'meta'; use 5.008001; extends 'Net::Google::Spreadsheets::Base'; use Carp; use Net::Google::AuthSub; use Net::Google::Spreadsheets::UserAgent; -use Net::Google::Spreadsheets::Spreadsheet; our $VERSION = '0.05'; BEGIN { $XML::Atom::DefaultVersion = 1; } -has +contents => ( +has spreadsheet_feed => ( + traits => ['Net::Google::Spreadsheets::Traits::Feed'], is => 'ro', - default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full' + isa => 'Str', + default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full', + entry_class => 'Net::Google::Spreadsheets::Spreadsheet', ); -has +service => ( - is => 'ro', - default => sub {return $_[0]}, -); +sub _build_service {return $_[0]} has source => ( isa => 'Str', is => 'ro', required => 1, default => sub { __PACKAGE__.'-'.$VERSION }, ); has username => ( isa => 'Str', is => 'ro', required => 1 ); has password => ( isa => 'Str', is => 'ro', required => 1 ); has ua => ( isa => 'Net::Google::Spreadsheets::UserAgent', is => 'ro', handles => [qw(request feed entry post put)], + required => 1, + lazy_build => 1, ); -sub BUILD { +sub _build_ua { my $self = shift; my $authsub = Net::Google::AuthSub->new( service => 'wise', source => $self->source, ); my $res = $authsub->login( $self->username, $self->password, ); unless ($res && $res->is_success) { croak 'Net::Google::AuthSub login failed'; } - $self->{ua} = Net::Google::Spreadsheets::UserAgent->new( + return Net::Google::Spreadsheets::UserAgent->new( source => $self->source, auth => $res->auth, ); } __PACKAGE__->meta->make_immutable; -sub spreadsheets { - my ($self, $args) = @_; - if ($args->{key}) { - my $atom = eval {$self->entry($self->contents.'/'.$args->{key})}; - $atom or return; - return Net::Google::Spreadsheets::Spreadsheet->new( - atom => $atom, - service => $self, - ); - } else { - my $cond = $args->{title} ? - { - title => $args->{title}, - 'title-exact' => 'true' - } : {}; - my $feed = $self->feed( - $self->contents, - $cond, - ); - return grep { - (!%$args && 1) - || - ($args->{title} && $_->title eq $args->{title}) - } map { - Net::Google::Spreadsheets::Spreadsheet->new( - atom => $_, - service => $self - ) - } $feed->entries; - } -} - -sub spreadsheet { - my ($self, $args) = @_; - return ($self->spreadsheets($args))[0]; +sub BUILD { + my ($self) = @_; + $self->ua; #check if login ok? } 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, {row => 1, col => 4, input_value => 'age'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # fetch rows my @rows = $worksheet->rows; # or fetch rows with query @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 4 =item username Username for Google. This should be full email address format like '[email protected]'. =item password Password corresponding to the username. =item source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 4 =item title title of the spreadsheet. =item title-exact whether title search should match exactly or not. =item key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 TESTING To test this module, you have to prepare as below. =over 4 =item create a spreadsheet by hand Go to L<http://docs.google.com> and create a spreadsheet. =item set SPREADSHEET_TITLE environment variable export SPREADSHEET_TITLE='my test spreadsheet' or so. =item set username and password for google.com via Config::Pit install Config::Pit and type ppit set google.com then some editor comes up and type your username and password like --- username: [email protected] password: foobarbaz =item run tests as always, perl Makefile.PL make make test =back =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Net/Google/Spreadsheets/Base.pm b/lib/Net/Google/Spreadsheets/Base.pm index 3ab2a76..39a842e 100644 --- a/lib/Net/Google/Spreadsheets/Base.pm +++ b/lib/Net/Google/Spreadsheets/Base.pm @@ -1,161 +1,147 @@ package Net::Google::Spreadsheets::Base; use Moose; use namespace::clean -except => 'meta'; use Carp; has service => ( isa => 'Net::Google::Spreadsheets', is => 'ro', required => 1, - lazy => 1, - default => sub { shift->container->service }, + lazy_build => 1, ); +sub _build_service { shift->container->service }; + my %ns = ( gd => 'http://schemas.google.com/g/2005', gs => 'http://schemas.google.com/spreadsheets/2006', gsx => 'http://schemas.google.com/spreadsheets/2006/extended', batch => 'http://schemas.google.com/gdata/batch', ); -my $pkg = __PACKAGE__; while (my ($prefix, $uri) = each %ns) { - no strict 'refs'; - *{"$pkg\::${prefix}ns"} = sub {XML::Atom::Namespace->new($prefix, $uri)}; + __PACKAGE__->meta->add_method( + "${prefix}ns" => sub { + XML::Atom::Namespace->new($prefix, $uri) + } + ); } my %rel2label = ( edit => 'editurl', self => 'selfurl', ); for (values %rel2label) { has $_ => (isa => 'Str', is => 'ro'); } -has accessor => ( - isa => 'Str', - is => 'ro', -); - has atom => ( isa => 'XML::Atom::Entry', is => 'rw', trigger => sub { my ($self, $arg) = @_; my $id = $self->atom->get($self->ns, 'id'); croak "can't set different id!" if $self->id && $self->id ne $id; $self->_update_atom; }, handles => ['ns', 'elem', 'author'], ); has id => ( isa => 'Str', is => 'ro', ); -has content => ( - isa => 'Str', - is => 'ro', -); - has title => ( isa => 'Str', is => 'rw', default => 'untitled', trigger => sub {$_[0]->update} ); has etag => ( isa => 'Str', is => 'rw', ); has container => ( isa => 'Maybe[Net::Google::Spreadsheets::Base]', is => 'ro', ); __PACKAGE__->meta->make_immutable; sub _update_atom { my ($self) = @_; $self->{title} = $self->atom->title; $self->{id} = $self->atom->get($self->ns, 'id'); $self->etag($self->elem->getAttributeNS($self->gdns->{uri}, 'etag')); for ($self->atom->link) { my $label = $rel2label{$_->rel} or next; $self->{$label} = $_->href; } } -sub list_contents { - my ($self, $class, $cond) = @_; - $self->content or return; - my $feed = $self->service->feed($self->content, $cond); - return map {$class->new(container => $self, atom => $_)} $feed->entries; -} - sub entry { my ($self) = @_; my $entry = XML::Atom::Entry->new; $entry->title($self->title) if $self->title; return $entry; } sub sync { my ($self) = @_; my $entry = $self->service->entry($self->selfurl); $self->atom($entry); } sub update { my ($self) = @_; $self->etag or return; my $atom = $self->service->put( { self => $self, entry => $self->entry, } ); $self->container->sync; $self->atom($atom); } sub delete { my $self = shift; my $res = $self->service->request( { uri => $self->editurl, method => 'DELETE', header => {'If-Match' => $self->etag}, } ); $self->container->sync if $res->is_success; return $res->is_success; } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Base - Base class of Net::Google::Spreadsheets::*. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Cell.pm b/lib/Net/Google/Spreadsheets/Cell.pm index 4e1a645..07cf78d 100644 --- a/lib/Net/Google/Spreadsheets/Cell.pm +++ b/lib/Net/Google/Spreadsheets/Cell.pm @@ -1,116 +1,121 @@ package Net::Google::Spreadsheets::Cell; use Moose; use namespace::clean -except => 'meta'; extends 'Net::Google::Spreadsheets::Base'; +has content => ( + isa => 'Str', + is => 'ro', +); + has row => ( isa => 'Int', is => 'ro', ); has col => ( isa => 'Int', is => 'ro', ); has input_value => ( isa => 'Str', is => 'rw', trigger => sub {$_[0]->update}, ); after _update_atom => sub { my ($self) = @_; my ($elem) = $self->elem->getElementsByTagNameNS($self->gsns->{uri}, 'cell'); $self->{row} = $elem->getAttribute('row'); $self->{col} = $elem->getAttribute('col'); $self->{input_value} = $elem->getAttribute('inputValue'); $self->{content} = $elem->textContent || ''; }; around entry => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->gsns, 'cell', '', { row => $self->row, col => $self->col, inputValue => $self->input_value, } ); my $link = XML::Atom::Link->new; $link->rel('edit'); $link->type('application/atom+xml'); $link->href($self->editurl); $entry->link($link); $entry->id($self->id); return $entry; }; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Cell - A representation class for Google Spreadsheet cell. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a cell my $cell = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->cell( { col => 1, row => 1, } ); # update a cell $cell->input_value('new value'); # get the content of a cell my $value = $cell->content; =head1 ATTRIBUTES =head2 input_value Rewritable attribute. You can set formula like '=A1+B1' or so. =head2 content Read only attribute. You can get the result of formula. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Row.pm b/lib/Net/Google/Spreadsheets/Row.pm index 1e7c8e1..424866c 100644 --- a/lib/Net/Google/Spreadsheets/Row.pm +++ b/lib/Net/Google/Spreadsheets/Row.pm @@ -1,152 +1,152 @@ package Net::Google::Spreadsheets::Row; use Moose; use namespace::clean -except => 'meta'; extends 'Net::Google::Spreadsheets::Base'; -has +content => ( +has content => ( isa => 'HashRef', is => 'rw', default => sub { +{} }, trigger => sub { $_[0]->update }, ); after _update_atom => sub { my ($self) = @_; for my $node ($self->elem->getElementsByTagNameNS($self->gsxns->{uri}, '*')) { $self->{content}->{$node->localname} = $node->textContent; } }; around entry => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->{content}}) { $entry->set($self->gsxns, $key, $value); } return $entry; }; __PACKAGE__->meta->make_immutable; sub param { my ($self, $arg) = @_; return $self->content unless $arg; if (ref $arg && (ref $arg eq 'HASH')) { return $self->content( { %{$self->content}, %$arg, } ); } else { return $self->content->{$arg}; } } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Row - A representation class for Google Spreadsheet row. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a row my $row = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->row( { sq => 'id = 1000' } ); # get the content of a row my $hashref = $row->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $row->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $row->param('name'); # returns 'Nobuo Danjou' my $newval = $row->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new row value (with all fields) my $hashref = $row->param; # same as $row->content; =head1 METHODS =head2 param sets and gets content value. =head1 CAVEATS Space characters in hash key of rows will be removed when you access rows. See below. my $ws = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'foobar' )->spreadsheet({titile => 'sample'})->worksheet(1); $ws->batchupdate_cell( {col => 1,row => 1, input_value => 'name'}, {col => 2,row => 1, input_value => 'mail address'}, ); $ws->add_row( { name => 'my name', mailaddress => '[email protected]', # above passes, below fails. # 'mail address' => '[email protected]', } ); =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Spreadsheet.pm b/lib/Net/Google/Spreadsheets/Spreadsheet.pm index ab91838..6d8eff5 100644 --- a/lib/Net/Google/Spreadsheets/Spreadsheet.pm +++ b/lib/Net/Google/Spreadsheets/Spreadsheet.pm @@ -1,122 +1,119 @@ package Net::Google::Spreadsheets::Spreadsheet; use Moose; use namespace::clean -except => 'meta'; extends 'Net::Google::Spreadsheets::Base'; use Net::Google::Spreadsheets::Worksheet; use Path::Class; has +title => ( is => 'ro', ); has key => ( isa => 'Str', is => 'ro', required => 1, - lazy => 1, + lazy_build => 1, +); + +sub _build_key { + my $self = shift; + my $key = file(URI->new($self->id)->path)->basename; + return $key; +} + +has worksheet_feed => ( + traits => ['Net::Google::Spreadsheets::Traits::Feed'], + is => 'rw', + isa => 'Str', + entry_class => 'Net::Google::Spreadsheets::Worksheet', + _update_atom => sub { + my ($self) = @_; + $self->{worksheet_feed} = $self->atom->content->elem->getAttribute('src'); + }, +); + +has table_feed => ( + traits => ['Net::Google::Spreadsheets::Traits::Feed'], + is => 'rw', + isa => 'Str', + entry_class => 'Net::Google::Spreadsheets::Table', default => sub { my $self = shift; - my $key = file(URI->new($self->id)->path)->basename; - return $key; + return sprintf('http://spreadsheets.google.com/feeds/%s/tables',$self->key); } ); -after _update_atom => sub { - my ($self) = @_; - $self->{content} = $self->atom->content->elem->getAttribute('src'); -}; - __PACKAGE__->meta->make_immutable; -sub worksheet { - my ($self, $cond) = @_; - return ($self->worksheets($cond))[0]; -} - -sub worksheets { - my ($self, $cond) = @_; - return $self->list_contents('Net::Google::Spreadsheets::Worksheet', $cond); -} - -sub add_worksheet { - my ($self, $args) = @_; - my $entry = Net::Google::Spreadsheets::Worksheet->new($args || {})->entry; - my $atom = $self->service->post($self->content, $entry); - $self->sync; - return Net::Google::Spreadsheets::Worksheet->new( - container => $self, - atom => $atom, - ); -} - 1; __END__ =head1 NAME Net::Google::Spreadsheets::Spreadsheet - Representation of spreadsheet. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); =head1 METHODS =head2 worksheets(\%condition) Returns a list of Net::Google::Spreadsheets::Worksheet objects. Acceptable arguments are: =over 4 =item title =item title-exact =back =head2 worksheet(\%condition) Returns first item of worksheets(\%condition) if available. =head2 add_worksheet(\%attribuets) Creates new worksheet and returns a Net::Google::Spreadsheets::Worksheet object representing it. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Table.pm b/lib/Net/Google/Spreadsheets/Table.pm new file mode 100644 index 0000000..d25a9e6 --- /dev/null +++ b/lib/Net/Google/Spreadsheets/Table.pm @@ -0,0 +1,130 @@ +package Net::Google::Spreadsheets::Table; +use Moose; +use namespace::clean -except => 'meta'; + +extends 'Net::Google::Spreadsheets::Base'; + +after _update_atom => sub { + my ($self) = @_; + for my $node ($self->elem->getElementsByTagNameNS($self->gsxns->{uri}, '*')) { + $self->{content}->{$node->localname} = $node->textContent; + } +}; + +around entry => sub { + my ($next, $self) = @_; + my $entry = $next->($self); + while (my ($key, $value) = each %{$self->{content}}) { + $entry->set($self->gsxns, $key, $value); + } + return $entry; +}; + +__PACKAGE__->meta->make_immutable; + +1; +__END__ + +=head1 NAME + +Net::Google::Spreadsheets::Table - A representation class for Google Spreadsheet table. + +=head1 SYNOPSIS + + use Net::Google::Spreadsheets; + + my $service = Net::Google::Spreadsheets->new( + username => '[email protected]', + password => 'mypassword', + ); + + # get a row + my $row = $service->spreadsheet( + { + title => 'list for new year cards', + } + )->worksheet( + { + title => 'Sheet1', + } + )->row( + { + sq => 'id = 1000' + } + ); + + # get the content of a row + my $hashref = $row->content; + my $id = $hashref->{id}; + my $address = $hashref->{address}; + + # update a row + $row->content( + { + id => 1000, + address => 'somewhere', + zip => '100-0001', + name => 'Nobuo Danjou', + } + ); + + # get and set values partially + + my $value = $row->param('name'); + # returns 'Nobuo Danjou' + + my $newval = $row->param({address => 'elsewhere'}); + # updates address (and keeps other fields) and returns new row value (with all fields) + + my $hashref = $row->param; + # same as $row->content; + +=head1 METHODS + +=head2 param + +sets and gets content value. + +=head1 CAVEATS + +Space characters in hash key of rows will be removed when you access rows. See below. + + my $ws = Net::Google::Spreadsheets->new( + username => '[email protected]', + password => 'foobar' + )->spreadsheet({titile => 'sample'})->worksheet(1); + $ws->batchupdate_cell( + {col => 1,row => 1, input_value => 'name'}, + {col => 2,row => 1, input_value => 'mail address'}, + ); + $ws->add_row( + { + name => 'my name', + mailaddress => '[email protected]', + # above passes, below fails. + # 'mail address' => '[email protected]', + } + ); + +=head1 ATTRIBUTES + +=head2 content + +Rewritable attribute. You can get and set the value. + +=head1 SEE ALSO + +L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/developers_guide_protocol.html> + +L<http://code.google.com/intl/en/apis/spreadsheets/docs/3.0/reference.html> + +L<Net::Google::AuthSub> + +L<Net::Google::Spreadsheets> + +=head1 AUTHOR + +Nobuo Danjou E<lt>[email protected]<gt> + +=cut + diff --git a/lib/Net/Google/Spreadsheets/Traits/Feed.pm b/lib/Net/Google/Spreadsheets/Traits/Feed.pm new file mode 100644 index 0000000..3e223a2 --- /dev/null +++ b/lib/Net/Google/Spreadsheets/Traits/Feed.pm @@ -0,0 +1,101 @@ +package Net::Google::Spreadsheets::Traits::Feed; +use Moose::Role; + +has entry_class => ( + is => 'ro', + isa => 'Str', + required => 1, +); + +has entry_arg_builder => ( + is => 'ro', + isa => 'CodeRef', + required => 1, + default => sub { + return sub { + my ($self, $args) = @_; + return $args || {}; + }; + }, +); + +has query_arg_builder => ( + is => 'ro', + isa => 'CodeRef', + required => 1, + default => sub { + return sub { + my ($self, $args) = @_; + return $args || {}; + }; + }, +); + +has _update_atom => ( + is => 'ro', + isa => 'CodeRef', + required => 1, + default => sub { + return sub {}; + } +); + +after install_accessors => sub { + my $attr = shift; + my $class = $attr->associated_class; + my $key = $attr->name; + + my $entry_class = $attr->entry_class; + my $arg_builder = $attr->entry_arg_builder; + my $query_builder = $attr->query_arg_builder; + my $_update_atom = $attr->_update_atom; + my $method_base = lc [ split('::', $entry_class) ]->[-1]; + + $class->add_method( + "add_${method_base}" => sub { + my ($self, $args) = @_; + Class::MOP::load_class($entry_class); + $args = $arg_builder->($self, $args); + my $entry = $entry_class->new($args)->entry; + my $atom = $self->service->post($self->$key, $entry); + $self->sync; + return $entry_class->new( + container => $self, + atom => $atom, + ); + } + ); + + $class->add_method( + "${method_base}s" => sub { + my ($self, $cond) = @_; + $self->$key or return; + Class::MOP::load_class($entry_class); + $cond = $query_builder->($self, $cond); + my $feed = $self->service->feed($self->$key, $cond); + return map { + $entry_class->new( + container => $self, + atom => $_, + ) + } $feed->entries; + } + ); + + $class->add_method( + $method_base => sub { + my ($self, $cond) = @_; + my $method = "${method_base}s"; + return [ $self->$method($cond) ]->[0]; + } + ); + + $class->add_after_method_modifier( + '_update_atom' => sub { + my $self = shift; + $_update_atom->($self); + } + ); +}; + +1; diff --git a/lib/Net/Google/Spreadsheets/UserAgent.pm b/lib/Net/Google/Spreadsheets/UserAgent.pm index 768cb7d..ba95962 100644 --- a/lib/Net/Google/Spreadsheets/UserAgent.pm +++ b/lib/Net/Google/Spreadsheets/UserAgent.pm @@ -1,147 +1,147 @@ package Net::Google::Spreadsheets::UserAgent; use Moose; use namespace::clean -except => 'meta'; use Carp; use LWP::UserAgent; use HTTP::Headers; use HTTP::Request; use URI; use XML::Atom::Entry; use XML::Atom::Feed; has source => ( isa => 'Str', is => 'ro', required => 1, ); has auth => ( isa => 'Str', is => 'rw', required => 1, ); has ua => ( isa => 'LWP::UserAgent', is => 'ro', required => 1, - lazy => 1, - default => sub { - my $self = shift; - my $ua = LWP::UserAgent->new( - agent => $self->source, - requests_redirectable => [], - ); - $ua->default_headers( - HTTP::Headers->new( - Authorization => sprintf('GoogleLogin auth=%s', $self->auth), - GData_Version => 2, - ) - ); - return $ua; - } + lazy_build => 1, ); +sub _build_ua { + my $self = shift; + my $ua = LWP::UserAgent->new( + agent => $self->source, + requests_redirectable => [], + ); + $ua->default_headers( + HTTP::Headers->new( + Authorization => sprintf('GoogleLogin auth=%s', $self->auth), + GData_Version => 2, + ) + ); + return $ua; +} __PACKAGE__->meta->make_immutable; sub request { my ($self, $args) = @_; my $method = delete $args->{method}; $method ||= $args->{content} ? 'POST' : 'GET'; my $uri = URI->new($args->{'uri'}); $uri->query_form($args->{query}) if $args->{query}; my $req = HTTP::Request->new($method => "$uri"); $req->content($args->{content}) if $args->{content}; $req->header('Content-Type' => $args->{content_type}) if $args->{content_type}; if ($args->{header}) { while (my @pair = each %{$args->{header}}) { $req->header(@pair); } } my $res = eval {$self->ua->request($req)}; if ($@ || !$res->is_success) { die sprintf("request for '%s' failed: %s", $uri, $@ || $res->status_line); } my $type = $res->content_type; if ($res->content_length && $type !~ m{^application/atom\+xml}) { die sprintf("Content-Type of response for '%s' is not 'application/atom+xml': %s", $uri, $type); } if (my $res_obj = $args->{response_object}) { my $obj = eval {$res_obj->new(\($res->content))}; croak sprintf("response for '%s' is broken: %s", $uri, $@) if $@; return $obj; } return $res; } sub feed { my ($self, $url, $query) = @_; return $self->request( { uri => $url, query => $query || undef, response_object => 'XML::Atom::Feed', } ); } sub entry { my ($self, $url, $query) = @_; return $self->request( { uri => $url, query => $query || undef, response_object => 'XML::Atom::Entry', } ); } sub post { my ($self, $url, $entry, $header) = @_; return $self->request( { uri => $url, content => $entry->as_xml, header => $header || undef, content_type => 'application/atom+xml', response_object => ref $entry, } ); } sub put { my ($self, $args) = @_; return $self->request( { method => 'PUT', uri => $args->{self}->editurl, content => $args->{entry}->as_xml, header => {'If-Match' => $args->{self}->etag }, content_type => 'application/atom+xml', response_object => 'XML::Atom::Entry', } ); } 1; __END__ =head1 NAME Net::Google::Spreadsheets::UserAgent - UserAgent for Net::Google::Spreadsheets. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Worksheet.pm b/lib/Net/Google/Spreadsheets/Worksheet.pm index dbd52dc..30f37d7 100644 --- a/lib/Net/Google/Spreadsheets/Worksheet.pm +++ b/lib/Net/Google/Spreadsheets/Worksheet.pm @@ -1,254 +1,252 @@ package Net::Google::Spreadsheets::Worksheet; use Moose; +use Carp; use namespace::clean -except => 'meta'; extends 'Net::Google::Spreadsheets::Base'; -use Net::Google::Spreadsheets::Row; use Net::Google::Spreadsheets::Cell; +has row_feed => ( + traits => ['Net::Google::Spreadsheets::Traits::Feed'], + is => 'ro', + isa => 'Str', + entry_class => 'Net::Google::Spreadsheets::Row', + entry_arg_builder => sub { + my ($self, $args) = @_; + return {content => $args}; + }, + _update_atom => sub { + my $self = shift; + $self->{row_feed} = $self->atom->content->elem->getAttribute('src'); + }, +); + +has cellsfeed => ( + traits => ['Net::Google::Spreadsheets::Traits::Feed'], + is => 'ro', + isa => 'Str', + entry_class => 'Net::Google::Spreadsheets::Cell', + entry_arg_builder => sub { + my ($self, $args) = @_; + croak 'you can\'t call add_cell!'; + }, + query_arg_builder => sub { + my ($self, $args) = @_; + if (my $col = delete $args->{col}) { + $args->{'max-col'} = $col; + $args->{'min-col'} = $col; + $args->{'return-empty'} = 'true'; + } + if (my $row = delete $args->{row}) { + $args->{'max-row'} = $row; + $args->{'min-row'} = $row; + $args->{'return-empty'} = 'true'; + } + return $args; + }, + _update_atom => sub { + my ($self) = @_; + ($self->{cellsfeed}) = map {$_->href} grep { + $_->rel eq 'http://schemas.google.com/spreadsheets/2006#cellsfeed' + } $self->atom->link; + } +); + has row_count => ( isa => 'Int', is => 'rw', default => 100, trigger => sub {$_[0]->update} ); has col_count => ( isa => 'Int', is => 'rw', default => 20, trigger => sub {$_[0]->update} ); -has cellsfeed => ( - isa => 'Str', - is => 'ro', -); - around entry => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->gsns, 'rowCount', $self->row_count); $entry->set($self->gsns, 'colCount', $self->col_count); return $entry; }; after _update_atom => sub { my ($self) = @_; - $self->{content} = $self->atom->content->elem->getAttribute('src'); - ($self->{cellsfeed}) = map {$_->href} grep { - $_->rel eq 'http://schemas.google.com/spreadsheets/2006#cellsfeed' - } $self->atom->link; $self->{row_count} = $self->atom->get($self->gsns, 'rowCount'); $self->{col_count} = $self->atom->get($self->gsns, 'colCount'); }; __PACKAGE__->meta->make_immutable; -sub rows { - my ($self, $cond) = @_; - return $self->list_contents('Net::Google::Spreadsheets::Row', $cond); -} - -sub row { - my ($self, $cond) = @_; - return ($self->rows($cond))[0]; -} - -sub cells { - my ($self, $cond) = @_; - my $feed = $self->service->feed($self->cellsfeed, $cond); - return map {Net::Google::Spreadsheets::Cell->new(container => $self, atom => $_)} $feed->entries; -} - -sub cell { - my ($self, $args) = @_; - $self->cellsfeed or return; - my $url = sprintf("%s/R%sC%s", $self->cellsfeed, $args->{row}, $args->{col}); - return Net::Google::Spreadsheets::Cell->new( - container => $self, - atom => $self->service->entry($url), - ); -} - sub batchupdate_cell { my ($self, @args) = @_; my $feed = XML::Atom::Feed->new; for ( @args ) { my $id = sprintf("%s/R%sC%s",$self->cellsfeed, $_->{row}, $_->{col}); $_->{id} = $_->{editurl} = $id; my $entry = Net::Google::Spreadsheets::Cell->new($_)->entry; $entry->set($self->batchns, operation => '', {type => 'update'}); $entry->set($self->batchns, id => $id); $feed->add_entry($entry); } my $res_feed = $self->service->post($self->cellsfeed."/batch", $feed, {'If-Match' => '*'}); $self->sync; return map { Net::Google::Spreadsheets::Cell->new( atom => $_, container => $self, ) } grep { my ($node) = $_->elem->getElementsByTagNameNS($self->batchns->{uri}, 'status'); $node->getAttribute('code') == 200; } $res_feed->entries; } -sub add_row { - my ($self, $args) = @_; - my $entry = Net::Google::Spreadsheets::Row->new( - content => $args, - )->entry; - my $atom = $self->service->post($self->content, $entry); - $self->sync; - return Net::Google::Spreadsheets::Row->new( - container => $self, - atom => $atom, - ); -} - 1; __END__ =head1 NAME Net::Google::Spreadsheets::Worksheet - Representation of worksheet. =head1 SYNOPSIS my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); my $ss = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); my $worksheet = $ss->worksheet({title => 'Sheet1'}); # update cell by batch request $worksheet->batchupdate_cell( {col => 1, row => 1, input_value => 'name'}, {col => 2, row => 1, input_value => 'nick'}, {col => 3, row => 1, input_value => 'mail'}, {col => 4, row => 1, input_value => 'age'}, ); # get a cell object my $cell = $worksheet->cell({col => 1, row => 1}); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # get rows my @rows = $worksheet->rows; # search rows @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); =head1 METHODS =head2 rows(\%condition) Returns a list of Net::Google::Spreadsheets::Row objects. Acceptable arguments are: =over 4 =item sq Structured query on the full text in the worksheet. see the URL below for detail. =item orderby Set column name to use for ordering. =item reverse Set 'true' or 'false'. The default is 'false'. =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html#ListParameters> for details. =head2 row(\%condition) Returns first item of spreadsheets(\%condition) if available. =head2 cells(\%args) Returns a list of Net::Google::Spreadsheets::Cell objects. Acceptable arguments are: =over 4 =item min-row =item max-row =item min-col =item max-col =item range =item return-empty =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html#CellParameters> for details. =head2 cell(\%args) Returns Net::Google::Spreadsheets::Cell object. Arguments are: =over 4 =item col =item row =back =head2 batchupdate_cell(@args) update multiple cells with a batch request. Pass a list of hash references containing: =over 4 =item col =item row =item input_value =back =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/xt/01_podspell.t b/xt/01_podspell.t index 3bb585f..5f27824 100644 --- a/xt/01_podspell.t +++ b/xt/01_podspell.t @@ -1,20 +1,21 @@ use Test::More; eval q{ use Test::Spelling }; plan skip_all => "Test::Spelling is not installed." if $@; add_stopwords(map { split /[\s\:\-]/ } <DATA>); $ENV{LANG} = 'C'; all_pod_files_spelling_ok('lib'); __DATA__ Nobuo Danjou [email protected] Net::Google::Spreadsheets API username google orderby UserAgent col min sq rewritable param +com
lopnor/Net-Google-Spreadsheets
53c34c3172e263bbc629e037f919becb2d506146
pods for row key with space characters
diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index fcf6d99..d442e43 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,269 +1,307 @@ package Net::Google::Spreadsheets; use Moose; use namespace::clean -except => 'meta'; use 5.008001; extends 'Net::Google::Spreadsheets::Base'; use Carp; use Net::Google::AuthSub; use Net::Google::Spreadsheets::UserAgent; use Net::Google::Spreadsheets::Spreadsheet; our $VERSION = '0.05'; BEGIN { $XML::Atom::DefaultVersion = 1; } has +contents => ( is => 'ro', default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full' ); has +service => ( is => 'ro', default => sub {return $_[0]}, ); has source => ( isa => 'Str', is => 'ro', required => 1, default => sub { __PACKAGE__.'-'.$VERSION }, ); has username => ( isa => 'Str', is => 'ro', required => 1 ); has password => ( isa => 'Str', is => 'ro', required => 1 ); has ua => ( isa => 'Net::Google::Spreadsheets::UserAgent', is => 'ro', handles => [qw(request feed entry post put)], ); sub BUILD { my $self = shift; my $authsub = Net::Google::AuthSub->new( service => 'wise', source => $self->source, ); my $res = $authsub->login( $self->username, $self->password, ); unless ($res && $res->is_success) { croak 'Net::Google::AuthSub login failed'; } $self->{ua} = Net::Google::Spreadsheets::UserAgent->new( source => $self->source, auth => $res->auth, ); } __PACKAGE__->meta->make_immutable; sub spreadsheets { my ($self, $args) = @_; if ($args->{key}) { my $atom = eval {$self->entry($self->contents.'/'.$args->{key})}; $atom or return; return Net::Google::Spreadsheets::Spreadsheet->new( atom => $atom, service => $self, ); } else { my $cond = $args->{title} ? { title => $args->{title}, 'title-exact' => 'true' } : {}; my $feed = $self->feed( $self->contents, $cond, ); return grep { (!%$args && 1) || ($args->{title} && $_->title eq $args->{title}) } map { Net::Google::Spreadsheets::Spreadsheet->new( atom => $_, service => $self ) } $feed->entries; } } sub spreadsheet { my ($self, $args) = @_; return ($self->spreadsheets($args))[0]; } 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, {row => 1, col => 4, input_value => 'age'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # fetch rows my @rows = $worksheet->rows; # or fetch rows with query @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 4 =item username Username for Google. This should be full email address format like '[email protected]'. =item password Password corresponding to the username. =item source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 4 =item title title of the spreadsheet. =item title-exact whether title search should match exactly or not. =item key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. +=head1 TESTING + +To test this module, you have to prepare as below. + +=over 4 + +=item create a spreadsheet by hand + +Go to L<http://docs.google.com> and create a spreadsheet. + +=item set SPREADSHEET_TITLE environment variable + + export SPREADSHEET_TITLE='my test spreadsheet' + +or so. + +=item set username and password for google.com via Config::Pit + +install Config::Pit and type + + ppit set google.com + +then some editor comes up and type your username and password like + + --- + username: [email protected] + password: foobarbaz + +=item run tests + +as always, + + perl Makefile.PL + make + make test + +=back + =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Net/Google/Spreadsheets/Row.pm b/lib/Net/Google/Spreadsheets/Row.pm index c8c9288..1e7c8e1 100644 --- a/lib/Net/Google/Spreadsheets/Row.pm +++ b/lib/Net/Google/Spreadsheets/Row.pm @@ -1,134 +1,152 @@ package Net::Google::Spreadsheets::Row; use Moose; use namespace::clean -except => 'meta'; extends 'Net::Google::Spreadsheets::Base'; has +content => ( isa => 'HashRef', is => 'rw', default => sub { +{} }, - trigger => sub { - $_[0]->update - }, + trigger => sub { $_[0]->update }, ); after _update_atom => sub { my ($self) = @_; for my $node ($self->elem->getElementsByTagNameNS($self->gsxns->{uri}, '*')) { $self->{content}->{$node->localname} = $node->textContent; } }; around entry => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->{content}}) { $entry->set($self->gsxns, $key, $value); } return $entry; }; __PACKAGE__->meta->make_immutable; sub param { my ($self, $arg) = @_; return $self->content unless $arg; if (ref $arg && (ref $arg eq 'HASH')) { return $self->content( { %{$self->content}, %$arg, } ); } else { return $self->content->{$arg}; } } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Row - A representation class for Google Spreadsheet row. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a row my $row = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->row( { sq => 'id = 1000' } ); # get the content of a row my $hashref = $row->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $row->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $row->param('name'); # returns 'Nobuo Danjou' my $newval = $row->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new row value (with all fields) my $hashref = $row->param; # same as $row->content; =head1 METHODS =head2 param sets and gets content value. +=head1 CAVEATS + +Space characters in hash key of rows will be removed when you access rows. See below. + + my $ws = Net::Google::Spreadsheets->new( + username => '[email protected]', + password => 'foobar' + )->spreadsheet({titile => 'sample'})->worksheet(1); + $ws->batchupdate_cell( + {col => 1,row => 1, input_value => 'name'}, + {col => 2,row => 1, input_value => 'mail address'}, + ); + $ws->add_row( + { + name => 'my name', + mailaddress => '[email protected]', + # above passes, below fails. + # 'mail address' => '[email protected]', + } + ); =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/t/05_rows.t b/t/05_rows.t index 82c92fb..e235a34 100644 --- a/t/05_rows.t +++ b/t/05_rows.t @@ -1,53 +1,53 @@ use t::Util; use Test::More; ok my $ws = spreadsheet->add_worksheet, 'add worksheet'; { is scalar $ws->rows, 0; $ws->batchupdate_cell( {col => 1, row => 1, input_value => 'name'}, - {col => 2, row => 1, input_value => 'mail'}, + {col => 2, row => 1, input_value => 'mail address'}, {col => 3, row => 1, input_value => 'nick'}, ); is scalar $ws->rows, 0; my $value = { name => 'Nobuo Danjou', - mail => '[email protected]', + mailaddress => '[email protected]', nick => 'lopnor', }; - my $row = $ws->add_row($value); + ok my $row = $ws->add_row($value); isa_ok $row, 'Net::Google::Spreadsheets::Row'; is_deeply $row->content, $value; is_deeply $row->param, $value; is $row->param('name'), $value->{name}; my $newval = {name => '檀上伸郎'}; is_deeply $row->param($newval), { %$value, %$newval, }; my $value2 = { name => 'Kazuhiro Osawa', nick => 'yappo', - mail => '', + mailaddress => '', }; $row->content($value2); is_deeply $row->content, $value2; is scalar $ws->rows, 1; ok $row->delete; is scalar $ws->rows, 0; } { $ws->add_row( { name => $_ } ) for qw(danjou lopnor soffritto); is scalar $ws->rows, 3; my $row = $ws->row({sq => 'name = "lopnor"'}); isa_ok $row, 'Net::Google::Spreadsheets::Row'; - is_deeply $row->content, {name => 'lopnor', nick => '', mail => ''}; + is_deeply $row->content, {name => 'lopnor', nick => '', mailaddress => ''}; } ok $ws->delete, 'delete worksheet'; done_testing; diff --git a/t/06_error.t b/t/06_error.t index 96b2950..c92bf79 100644 --- a/t/06_error.t +++ b/t/06_error.t @@ -1,75 +1,78 @@ use strict; use Test::More; use Test::Exception; use Test::MockModule; use Test::MockObject; use LWP::UserAgent; use Net::Google::Spreadsheets; throws_ok { my $service = Net::Google::Spreadsheets->new( username => 'foo', password => 'bar', ); } qr{Net::Google::AuthSub login failed}; { my $res = Test::MockObject->new; $res->mock(is_success => sub {return 1}); $res->mock(auth => sub {return 'foobar'}); my $auth = Test::MockModule->new('Net::Google::AuthSub'); $auth->mock('login' => sub {return $res}); ok my $service = Net::Google::Spreadsheets->new( username => 'foo', password => 'bar', ); is $service->ua->auth, 'foobar'; my $ua = Test::MockModule->new('LWP::UserAgent'); { - $ua->mock('request' => sub {return HTTP::Response->new(302)}); + $ua->mock('request' => sub {return HTTP::Response->parse(<<'END')}); +302 Found +Location: http://www.google.com/ +END throws_ok { $service->spreadsheets; } qr{302 Found}; } { $ua->mock('request' => sub {return HTTP::Response->parse(<<END)}); 200 OK Content-Type: application/atom+xml Content-Length: 1 1 END throws_ok { $service->spreadsheets; } qr{broken}; } { $ua->mock('request' => sub {return HTTP::Response->parse(<<END)}); 200 OK Content-Type: text/html Content-Length: 13 <html></html> END throws_ok { $service->spreadsheets; } qr{is not 'application/atom\+xml'}; } { $ua->mock('request' => sub {return HTTP::Response->parse(<<'END')}); 200 OK ETag: W/"hogehoge" Content-Type: application/atom+xml; charset=UTF-8; type=feed Content-Length: 958 <?xml version='1.0' encoding='UTF-8'?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearch/1.1/' xmlns:gd='http://schemas.google.com/g/2005' gd:etag='W/&quot;hogehoge&quot;'><id>http://spreadsheets.google.com/feeds/spreadsheets/private/full</id><updated>2009-08-15T09:41:23.289Z</updated><category scheme='http://schemas.google.com/spreadsheets/2006' term='http://schemas.google.com/spreadsheets/2006#spreadsheet'/><title>Available Spreadsheets - [email protected]</title><link rel='alternate' type='text/html' href='http://docs.google.com'/><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://spreadsheets.google.com/feeds/spreadsheets/private/full'/><link rel='self' type='application/atom+xml' href='http://spreadsheets.google.com/feeds/spreadsheets/private/full?tfe='/><openSearch:totalResults>0</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex></feed> END my @ss = $service->spreadsheets; is scalar @ss, 0; } } done_testing; diff --git a/t/Util.pm b/t/Util.pm index d45648c..e1d024d 100644 --- a/t/Util.pm +++ b/t/Util.pm @@ -1,124 +1,124 @@ package t::Util; use strict; use warnings; use utf8; use Test::More; use Net::Google::Spreadsheets; sub PIT_KEY { 'google.com' } our $SPREADSHEET_TITLE; my ( $config, $service, ); BEGIN { my $builder = Test::More->builder; binmode($builder->output, ':utf8'); binmode($builder->failure_output, ':utf8'); binmode($builder->todo_output, ':utf8'); } sub import { my ($class, %args) = @_; my $caller = caller; strict->import; warnings->import; utf8->import; check_env(qw( - TEST_NET_GOOGLE_SPREADSHEETS_TITLE + SPREADSHEETS_TITLE )) or exit; { no warnings; check_use(qw(Config::Pit)) or exit; } check_config(PIT_KEY) or exit; - $SPREADSHEET_TITLE = $ENV{TEST_NET_GOOGLE_SPREADSHEETS_TITLE}; + $SPREADSHEET_TITLE = $ENV{SPREADSHEETS_TITLE}; check_spreadsheet_exists({title => $SPREADSHEET_TITLE}) or exit; { no strict 'refs'; for (qw(config service spreadsheet)) { *{"$caller\::$_"} = \&{$_}; } } } sub check_env { my (@env) = @_; for (@env) { unless ($ENV{$_}) { plan skip_all => "set $_ to run this test"; return; } } return 1; } sub check_use { my (@module) = @_; for (@module) { eval "use $_"; if ($@) { plan skip_all => "this test needs $_"; return; } } 1; } sub check_config { my $key = shift; my $config = &config($key); unless ($config) { plan skip_all => "set username and password for $key via 'ppit set $key'"; return; } return $config; } sub check_spreadsheet_exists { my ($args) = @_; $args->{title} or return 1; my $service = &service or die; my $sheet = $service->spreadsheet({title => $args->{title}}); unless ($sheet) { plan skip_all => "spreadsheet named '$args->{title}' doesn't exist"; return; } return $sheet; } sub config { my $key = shift; return $config if $config; my $c = Config::Pit::get($key); unless ($c->{username} && $c->{password}) { return; } $config = $c; return $config; } sub service { return $service if $service; my $c = &config or return; my $s = Net::Google::Spreadsheets->new( { username => $c->{username}, password => $c->{password}, } ) or return; $service = $s; return $service; } sub spreadsheet { my $title = shift || $SPREADSHEET_TITLE; return service->spreadsheet({title => $title}); } 1;
lopnor/Net-Google-Spreadsheets
61a87efb050b871e0a05740d5978bda58ee71dfe
more tests
diff --git a/t/06_error.t b/t/06_error.t index ac65400..96b2950 100644 --- a/t/06_error.t +++ b/t/06_error.t @@ -1,65 +1,75 @@ use strict; use Test::More; use Test::Exception; use Test::MockModule; use Test::MockObject; use LWP::UserAgent; use Net::Google::Spreadsheets; throws_ok { my $service = Net::Google::Spreadsheets->new( username => 'foo', password => 'bar', ); } qr{Net::Google::AuthSub login failed}; { my $res = Test::MockObject->new; $res->mock(is_success => sub {return 1}); $res->mock(auth => sub {return 'foobar'}); my $auth = Test::MockModule->new('Net::Google::AuthSub'); $auth->mock('login' => sub {return $res}); ok my $service = Net::Google::Spreadsheets->new( username => 'foo', password => 'bar', ); is $service->ua->auth, 'foobar'; + my $ua = Test::MockModule->new('LWP::UserAgent'); { - my $ua = Test::MockModule->new('LWP::UserAgent'); $ua->mock('request' => sub {return HTTP::Response->new(302)}); throws_ok { $service->spreadsheets; } qr{302 Found}; } { - my $ua = Test::MockModule->new('LWP::UserAgent'); $ua->mock('request' => sub {return HTTP::Response->parse(<<END)}); 200 OK Content-Type: application/atom+xml Content-Length: 1 1 END throws_ok { $service->spreadsheets; } qr{broken}; } { - my $ua = Test::MockModule->new('LWP::UserAgent'); $ua->mock('request' => sub {return HTTP::Response->parse(<<END)}); 200 OK Content-Type: text/html Content-Length: 13 <html></html> END throws_ok { $service->spreadsheets; } qr{is not 'application/atom\+xml'}; } + { + $ua->mock('request' => sub {return HTTP::Response->parse(<<'END')}); +200 OK +ETag: W/"hogehoge" +Content-Type: application/atom+xml; charset=UTF-8; type=feed +Content-Length: 958 + +<?xml version='1.0' encoding='UTF-8'?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearch/1.1/' xmlns:gd='http://schemas.google.com/g/2005' gd:etag='W/&quot;hogehoge&quot;'><id>http://spreadsheets.google.com/feeds/spreadsheets/private/full</id><updated>2009-08-15T09:41:23.289Z</updated><category scheme='http://schemas.google.com/spreadsheets/2006' term='http://schemas.google.com/spreadsheets/2006#spreadsheet'/><title>Available Spreadsheets - [email protected]</title><link rel='alternate' type='text/html' href='http://docs.google.com'/><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://spreadsheets.google.com/feeds/spreadsheets/private/full'/><link rel='self' type='application/atom+xml' href='http://spreadsheets.google.com/feeds/spreadsheets/private/full?tfe='/><openSearch:totalResults>0</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex></feed> +END + my @ss = $service->spreadsheets; + is scalar @ss, 0; + } } done_testing; diff --git a/t/Util.pm b/t/Util.pm index 1856ab9..d45648c 100644 --- a/t/Util.pm +++ b/t/Util.pm @@ -1,125 +1,124 @@ package t::Util; use strict; use warnings; use utf8; use Test::More; use Net::Google::Spreadsheets; sub PIT_KEY { 'google.com' } our $SPREADSHEET_TITLE; my ( $config, $service, ); BEGIN { my $builder = Test::More->builder; binmode($builder->output, ':utf8'); binmode($builder->failure_output, ':utf8'); binmode($builder->todo_output, ':utf8'); } sub import { my ($class, %args) = @_; my $caller = caller; strict->import; warnings->import; utf8->import; check_env(qw( - TEST_NET_GOOGLE_SPREADSHEETS TEST_NET_GOOGLE_SPREADSHEETS_TITLE )) or exit; { no warnings; check_use(qw(Config::Pit)) or exit; } check_config(PIT_KEY) or exit; $SPREADSHEET_TITLE = $ENV{TEST_NET_GOOGLE_SPREADSHEETS_TITLE}; check_spreadsheet_exists({title => $SPREADSHEET_TITLE}) or exit; { no strict 'refs'; for (qw(config service spreadsheet)) { *{"$caller\::$_"} = \&{$_}; } } } sub check_env { my (@env) = @_; for (@env) { unless ($ENV{$_}) { plan skip_all => "set $_ to run this test"; return; } } return 1; } sub check_use { my (@module) = @_; for (@module) { eval "use $_"; if ($@) { plan skip_all => "this test needs $_"; return; } } 1; } sub check_config { my $key = shift; my $config = &config($key); unless ($config) { plan skip_all => "set username and password for $key via 'ppit set $key'"; return; } return $config; } sub check_spreadsheet_exists { my ($args) = @_; $args->{title} or return 1; my $service = &service or die; my $sheet = $service->spreadsheet({title => $args->{title}}); unless ($sheet) { plan skip_all => "spreadsheet named '$args->{title}' doesn't exist"; return; } return $sheet; } sub config { my $key = shift; return $config if $config; my $c = Config::Pit::get($key); unless ($c->{username} && $c->{password}) { return; } $config = $c; return $config; } sub service { return $service if $service; my $c = &config or return; my $s = Net::Google::Spreadsheets->new( { username => $c->{username}, password => $c->{password}, } ) or return; $service = $s; return $service; } sub spreadsheet { my $title = shift || $SPREADSHEET_TITLE; return service->spreadsheet({title => $title}); } 1;
lopnor/Net-Google-Spreadsheets
aa6f18abf06a6c620e86da32dcf37478a1fb73de
better error handling
diff --git a/Makefile.PL b/Makefile.PL index afd098c..e87f078 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,21 +1,23 @@ use inc::Module::Install; name 'Net-Google-Spreadsheets'; all_from 'lib/Net/Google/Spreadsheets.pm'; requires 'Carp'; requires 'XML::Atom'; requires 'Net::Google::AuthSub'; requires 'Crypt::SSLeay'; requires 'LWP::UserAgent'; requires 'URI'; requires 'Moose' => 0.34; requires 'Path::Class'; tests 't/*.t'; author_tests 'xt'; -build_requires 'Test::More'; +build_requires 'Test::More' => '0.88'; build_requires 'Test::Exception'; +build_requires 'Test::MockModule'; +build_requires 'Test::MockObject'; use_test_base; auto_include; WriteAll; diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index bfb4cef..fcf6d99 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,266 +1,269 @@ package Net::Google::Spreadsheets; use Moose; +use namespace::clean -except => 'meta'; use 5.008001; extends 'Net::Google::Spreadsheets::Base'; use Carp; use Net::Google::AuthSub; use Net::Google::Spreadsheets::UserAgent; use Net::Google::Spreadsheets::Spreadsheet; our $VERSION = '0.05'; BEGIN { $XML::Atom::DefaultVersion = 1; } has +contents => ( is => 'ro', default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full' ); has +service => ( is => 'ro', default => sub {return $_[0]}, ); has source => ( isa => 'Str', is => 'ro', required => 1, default => sub { __PACKAGE__.'-'.$VERSION }, ); has username => ( isa => 'Str', is => 'ro', required => 1 ); has password => ( isa => 'Str', is => 'ro', required => 1 ); has ua => ( isa => 'Net::Google::Spreadsheets::UserAgent', is => 'ro', handles => [qw(request feed entry post put)], ); sub BUILD { my $self = shift; my $authsub = Net::Google::AuthSub->new( service => 'wise', source => $self->source, ); my $res = $authsub->login( $self->username, $self->password, ); unless ($res && $res->is_success) { croak 'Net::Google::AuthSub login failed'; } $self->{ua} = Net::Google::Spreadsheets::UserAgent->new( source => $self->source, auth => $res->auth, ); } +__PACKAGE__->meta->make_immutable; + sub spreadsheets { my ($self, $args) = @_; if ($args->{key}) { my $atom = eval {$self->entry($self->contents.'/'.$args->{key})}; $atom or return; return Net::Google::Spreadsheets::Spreadsheet->new( atom => $atom, service => $self, ); } else { my $cond = $args->{title} ? { title => $args->{title}, 'title-exact' => 'true' } : {}; my $feed = $self->feed( $self->contents, $cond, ); return grep { (!%$args && 1) || ($args->{title} && $_->title eq $args->{title}) } map { Net::Google::Spreadsheets::Spreadsheet->new( atom => $_, service => $self ) } $feed->entries; } } sub spreadsheet { my ($self, $args) = @_; return ($self->spreadsheets($args))[0]; } 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, {row => 1, col => 4, input_value => 'age'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # fetch rows my @rows = $worksheet->rows; # or fetch rows with query @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 4 =item username Username for Google. This should be full email address format like '[email protected]'. =item password Password corresponding to the username. =item source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 4 =item title title of the spreadsheet. =item title-exact whether title search should match exactly or not. =item key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Net/Google/Spreadsheets/Base.pm b/lib/Net/Google/Spreadsheets/Base.pm index 6a92d73..3ab2a76 100644 --- a/lib/Net/Google/Spreadsheets/Base.pm +++ b/lib/Net/Google/Spreadsheets/Base.pm @@ -1,161 +1,161 @@ package Net::Google::Spreadsheets::Base; use Moose; +use namespace::clean -except => 'meta'; use Carp; has service => ( isa => 'Net::Google::Spreadsheets', is => 'ro', required => 1, lazy => 1, default => sub { shift->container->service }, ); my %ns = ( gd => 'http://schemas.google.com/g/2005', gs => 'http://schemas.google.com/spreadsheets/2006', gsx => 'http://schemas.google.com/spreadsheets/2006/extended', batch => 'http://schemas.google.com/gdata/batch', ); +my $pkg = __PACKAGE__; while (my ($prefix, $uri) = each %ns) { - has $prefix.'ns' => ( - isa => 'XML::Atom::Namespace', - is => 'ro', - required => 1, - default => sub {XML::Atom::Namespace->new($prefix, $uri)}, - ); + no strict 'refs'; + *{"$pkg\::${prefix}ns"} = sub {XML::Atom::Namespace->new($prefix, $uri)}; } my %rel2label = ( edit => 'editurl', self => 'selfurl', ); for (values %rel2label) { has $_ => (isa => 'Str', is => 'ro'); } has accessor => ( isa => 'Str', is => 'ro', ); has atom => ( isa => 'XML::Atom::Entry', is => 'rw', trigger => sub { my ($self, $arg) = @_; my $id = $self->atom->get($self->ns, 'id'); croak "can't set different id!" if $self->id && $self->id ne $id; $self->_update_atom; }, handles => ['ns', 'elem', 'author'], ); has id => ( isa => 'Str', is => 'ro', ); has content => ( isa => 'Str', is => 'ro', ); has title => ( isa => 'Str', is => 'rw', default => 'untitled', trigger => sub {$_[0]->update} ); has etag => ( isa => 'Str', is => 'rw', ); has container => ( isa => 'Maybe[Net::Google::Spreadsheets::Base]', is => 'ro', ); +__PACKAGE__->meta->make_immutable; + sub _update_atom { my ($self) = @_; $self->{title} = $self->atom->title; $self->{id} = $self->atom->get($self->ns, 'id'); $self->etag($self->elem->getAttributeNS($self->gdns->{uri}, 'etag')); for ($self->atom->link) { my $label = $rel2label{$_->rel} or next; $self->{$label} = $_->href; } } sub list_contents { my ($self, $class, $cond) = @_; $self->content or return; my $feed = $self->service->feed($self->content, $cond); return map {$class->new(container => $self, atom => $_)} $feed->entries; } sub entry { my ($self) = @_; my $entry = XML::Atom::Entry->new; $entry->title($self->title) if $self->title; return $entry; } sub sync { my ($self) = @_; my $entry = $self->service->entry($self->selfurl); $self->atom($entry); } sub update { my ($self) = @_; $self->etag or return; my $atom = $self->service->put( { self => $self, entry => $self->entry, } ); $self->container->sync; $self->atom($atom); } sub delete { my $self = shift; my $res = $self->service->request( { uri => $self->editurl, method => 'DELETE', header => {'If-Match' => $self->etag}, } ); $self->container->sync if $res->is_success; return $res->is_success; } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Base - Base class of Net::Google::Spreadsheets::*. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Cell.pm b/lib/Net/Google/Spreadsheets/Cell.pm index 58bf095..4e1a645 100644 --- a/lib/Net/Google/Spreadsheets/Cell.pm +++ b/lib/Net/Google/Spreadsheets/Cell.pm @@ -1,113 +1,116 @@ package Net::Google::Spreadsheets::Cell; use Moose; +use namespace::clean -except => 'meta'; extends 'Net::Google::Spreadsheets::Base'; has row => ( isa => 'Int', is => 'ro', ); has col => ( isa => 'Int', is => 'ro', ); has input_value => ( isa => 'Str', is => 'rw', trigger => sub {$_[0]->update}, ); after _update_atom => sub { my ($self) = @_; my ($elem) = $self->elem->getElementsByTagNameNS($self->gsns->{uri}, 'cell'); $self->{row} = $elem->getAttribute('row'); $self->{col} = $elem->getAttribute('col'); $self->{input_value} = $elem->getAttribute('inputValue'); $self->{content} = $elem->textContent || ''; }; around entry => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->gsns, 'cell', '', { row => $self->row, col => $self->col, inputValue => $self->input_value, } ); my $link = XML::Atom::Link->new; $link->rel('edit'); $link->type('application/atom+xml'); $link->href($self->editurl); $entry->link($link); $entry->id($self->id); return $entry; }; +__PACKAGE__->meta->make_immutable; + 1; __END__ =head1 NAME Net::Google::Spreadsheets::Cell - A representation class for Google Spreadsheet cell. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a cell my $cell = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->cell( { col => 1, row => 1, } ); # update a cell $cell->input_value('new value'); # get the content of a cell my $value = $cell->content; =head1 ATTRIBUTES =head2 input_value Rewritable attribute. You can set formula like '=A1+B1' or so. =head2 content Read only attribute. You can get the result of formula. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Row.pm b/lib/Net/Google/Spreadsheets/Row.pm index 3941e13..c8c9288 100644 --- a/lib/Net/Google/Spreadsheets/Row.pm +++ b/lib/Net/Google/Spreadsheets/Row.pm @@ -1,131 +1,134 @@ package Net::Google::Spreadsheets::Row; use Moose; +use namespace::clean -except => 'meta'; extends 'Net::Google::Spreadsheets::Base'; has +content => ( isa => 'HashRef', is => 'rw', default => sub { +{} }, trigger => sub { $_[0]->update }, ); after _update_atom => sub { my ($self) = @_; for my $node ($self->elem->getElementsByTagNameNS($self->gsxns->{uri}, '*')) { $self->{content}->{$node->localname} = $node->textContent; } }; around entry => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->{content}}) { $entry->set($self->gsxns, $key, $value); } return $entry; }; +__PACKAGE__->meta->make_immutable; + sub param { my ($self, $arg) = @_; return $self->content unless $arg; if (ref $arg && (ref $arg eq 'HASH')) { return $self->content( { %{$self->content}, %$arg, } ); } else { return $self->content->{$arg}; } } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Row - A representation class for Google Spreadsheet row. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a row my $row = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->row( { sq => 'id = 1000' } ); # get the content of a row my $hashref = $row->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $row->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); # get and set values partially my $value = $row->param('name'); # returns 'Nobuo Danjou' my $newval = $row->param({address => 'elsewhere'}); # updates address (and keeps other fields) and returns new row value (with all fields) my $hashref = $row->param; # same as $row->content; =head1 METHODS =head2 param sets and gets content value. =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Spreadsheet.pm b/lib/Net/Google/Spreadsheets/Spreadsheet.pm index 8a8431e..ab91838 100644 --- a/lib/Net/Google/Spreadsheets/Spreadsheet.pm +++ b/lib/Net/Google/Spreadsheets/Spreadsheet.pm @@ -1,118 +1,122 @@ package Net::Google::Spreadsheets::Spreadsheet; use Moose; -use Net::Google::Spreadsheets::Worksheet; -use Path::Class; +use namespace::clean -except => 'meta'; extends 'Net::Google::Spreadsheets::Base'; +use Net::Google::Spreadsheets::Worksheet; +use Path::Class; + has +title => ( is => 'ro', ); has key => ( isa => 'Str', is => 'ro', required => 1, lazy => 1, default => sub { my $self = shift; my $key = file(URI->new($self->id)->path)->basename; return $key; } ); after _update_atom => sub { my ($self) = @_; $self->{content} = $self->atom->content->elem->getAttribute('src'); }; +__PACKAGE__->meta->make_immutable; + sub worksheet { my ($self, $cond) = @_; return ($self->worksheets($cond))[0]; } sub worksheets { my ($self, $cond) = @_; return $self->list_contents('Net::Google::Spreadsheets::Worksheet', $cond); } sub add_worksheet { my ($self, $args) = @_; my $entry = Net::Google::Spreadsheets::Worksheet->new($args || {})->entry; my $atom = $self->service->post($self->content, $entry); $self->sync; return Net::Google::Spreadsheets::Worksheet->new( container => $self, atom => $atom, ); } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Spreadsheet - Representation of spreadsheet. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); =head1 METHODS =head2 worksheets(\%condition) Returns a list of Net::Google::Spreadsheets::Worksheet objects. Acceptable arguments are: =over 4 =item title =item title-exact =back =head2 worksheet(\%condition) Returns first item of worksheets(\%condition) if available. =head2 add_worksheet(\%attribuets) Creates new worksheet and returns a Net::Google::Spreadsheets::Worksheet object representing it. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/UserAgent.pm b/lib/Net/Google/Spreadsheets/UserAgent.pm index c4d6c78..768cb7d 100644 --- a/lib/Net/Google/Spreadsheets/UserAgent.pm +++ b/lib/Net/Google/Spreadsheets/UserAgent.pm @@ -1,134 +1,147 @@ package Net::Google::Spreadsheets::UserAgent; use Moose; +use namespace::clean -except => 'meta'; use Carp; use LWP::UserAgent; use HTTP::Headers; use HTTP::Request; use URI; use XML::Atom::Entry; use XML::Atom::Feed; has source => ( isa => 'Str', is => 'ro', required => 1, ); has auth => ( isa => 'Str', is => 'rw', required => 1, ); has ua => ( isa => 'LWP::UserAgent', is => 'ro', required => 1, lazy => 1, default => sub { my $self = shift; my $ua = LWP::UserAgent->new( agent => $self->source, + requests_redirectable => [], ); $ua->default_headers( HTTP::Headers->new( Authorization => sprintf('GoogleLogin auth=%s', $self->auth), GData_Version => 2, ) ); return $ua; } ); +__PACKAGE__->meta->make_immutable; + sub request { my ($self, $args) = @_; my $method = delete $args->{method}; $method ||= $args->{content} ? 'POST' : 'GET'; my $uri = URI->new($args->{'uri'}); $uri->query_form($args->{query}) if $args->{query}; my $req = HTTP::Request->new($method => "$uri"); $req->content($args->{content}) if $args->{content}; $req->header('Content-Type' => $args->{content_type}) if $args->{content_type}; if ($args->{header}) { while (my @pair = each %{$args->{header}}) { $req->header(@pair); } } - my $res = $self->ua->request($req); - unless ($res->is_success) { - die sprintf("request for '%s' failed: %s", $uri, $res->status_line); + my $res = eval {$self->ua->request($req)}; + if ($@ || !$res->is_success) { + die sprintf("request for '%s' failed: %s", $uri, $@ || $res->status_line); + } + my $type = $res->content_type; + if ($res->content_length && $type !~ m{^application/atom\+xml}) { + die sprintf("Content-Type of response for '%s' is not 'application/atom+xml': %s", $uri, $type); + } + if (my $res_obj = $args->{response_object}) { + my $obj = eval {$res_obj->new(\($res->content))}; + croak sprintf("response for '%s' is broken: %s", $uri, $@) if $@; + return $obj; } return $res; } sub feed { my ($self, $url, $query) = @_; - my $res = $self->request( + return $self->request( { uri => $url, query => $query || undef, + response_object => 'XML::Atom::Feed', } ); - return XML::Atom::Feed->new(\($res->content)); } sub entry { my ($self, $url, $query) = @_; - my $res = $self->request( + return $self->request( { uri => $url, query => $query || undef, + response_object => 'XML::Atom::Entry', } ); - return XML::Atom::Entry->new(\($res->content)); } sub post { my ($self, $url, $entry, $header) = @_; - my $res = $self->request( + return $self->request( { uri => $url, content => $entry->as_xml, header => $header || undef, content_type => 'application/atom+xml', + response_object => ref $entry, } ); - return (ref $entry)->new(\($res->content)); } sub put { my ($self, $args) = @_; - my $res = $self->request( + return $self->request( { method => 'PUT', uri => $args->{self}->editurl, content => $args->{entry}->as_xml, header => {'If-Match' => $args->{self}->etag }, content_type => 'application/atom+xml', + response_object => 'XML::Atom::Entry', } ); - return XML::Atom::Entry->new(\($res->content)); } 1; __END__ =head1 NAME Net::Google::Spreadsheets::UserAgent - UserAgent for Net::Google::Spreadsheets. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Worksheet.pm b/lib/Net/Google/Spreadsheets/Worksheet.pm index 3450adc..dbd52dc 100644 --- a/lib/Net/Google/Spreadsheets/Worksheet.pm +++ b/lib/Net/Google/Spreadsheets/Worksheet.pm @@ -1,250 +1,254 @@ package Net::Google::Spreadsheets::Worksheet; use Moose; -use Net::Google::Spreadsheets::Row; -use Net::Google::Spreadsheets::Cell; +use namespace::clean -except => 'meta'; extends 'Net::Google::Spreadsheets::Base'; +use Net::Google::Spreadsheets::Row; +use Net::Google::Spreadsheets::Cell; + has row_count => ( isa => 'Int', is => 'rw', default => 100, trigger => sub {$_[0]->update} ); has col_count => ( isa => 'Int', is => 'rw', default => 20, trigger => sub {$_[0]->update} ); has cellsfeed => ( isa => 'Str', is => 'ro', ); around entry => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->gsns, 'rowCount', $self->row_count); $entry->set($self->gsns, 'colCount', $self->col_count); return $entry; }; after _update_atom => sub { my ($self) = @_; $self->{content} = $self->atom->content->elem->getAttribute('src'); ($self->{cellsfeed}) = map {$_->href} grep { $_->rel eq 'http://schemas.google.com/spreadsheets/2006#cellsfeed' } $self->atom->link; $self->{row_count} = $self->atom->get($self->gsns, 'rowCount'); $self->{col_count} = $self->atom->get($self->gsns, 'colCount'); }; +__PACKAGE__->meta->make_immutable; + sub rows { my ($self, $cond) = @_; return $self->list_contents('Net::Google::Spreadsheets::Row', $cond); } sub row { my ($self, $cond) = @_; return ($self->rows($cond))[0]; } sub cells { my ($self, $cond) = @_; my $feed = $self->service->feed($self->cellsfeed, $cond); return map {Net::Google::Spreadsheets::Cell->new(container => $self, atom => $_)} $feed->entries; } sub cell { my ($self, $args) = @_; $self->cellsfeed or return; my $url = sprintf("%s/R%sC%s", $self->cellsfeed, $args->{row}, $args->{col}); return Net::Google::Spreadsheets::Cell->new( container => $self, atom => $self->service->entry($url), ); } sub batchupdate_cell { my ($self, @args) = @_; my $feed = XML::Atom::Feed->new; for ( @args ) { my $id = sprintf("%s/R%sC%s",$self->cellsfeed, $_->{row}, $_->{col}); $_->{id} = $_->{editurl} = $id; my $entry = Net::Google::Spreadsheets::Cell->new($_)->entry; $entry->set($self->batchns, operation => '', {type => 'update'}); $entry->set($self->batchns, id => $id); $feed->add_entry($entry); } my $res_feed = $self->service->post($self->cellsfeed."/batch", $feed, {'If-Match' => '*'}); $self->sync; return map { Net::Google::Spreadsheets::Cell->new( atom => $_, container => $self, ) } grep { my ($node) = $_->elem->getElementsByTagNameNS($self->batchns->{uri}, 'status'); $node->getAttribute('code') == 200; } $res_feed->entries; } sub add_row { my ($self, $args) = @_; my $entry = Net::Google::Spreadsheets::Row->new( content => $args, )->entry; my $atom = $self->service->post($self->content, $entry); $self->sync; return Net::Google::Spreadsheets::Row->new( container => $self, atom => $atom, ); } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Worksheet - Representation of worksheet. =head1 SYNOPSIS my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); my $ss = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); my $worksheet = $ss->worksheet({title => 'Sheet1'}); # update cell by batch request $worksheet->batchupdate_cell( {col => 1, row => 1, input_value => 'name'}, {col => 2, row => 1, input_value => 'nick'}, {col => 3, row => 1, input_value => 'mail'}, {col => 4, row => 1, input_value => 'age'}, ); # get a cell object my $cell = $worksheet->cell({col => 1, row => 1}); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # get rows my @rows = $worksheet->rows; # search rows @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); =head1 METHODS =head2 rows(\%condition) Returns a list of Net::Google::Spreadsheets::Row objects. Acceptable arguments are: =over 4 =item sq Structured query on the full text in the worksheet. see the URL below for detail. =item orderby Set column name to use for ordering. =item reverse Set 'true' or 'false'. The default is 'false'. =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html#ListParameters> for details. =head2 row(\%condition) Returns first item of spreadsheets(\%condition) if available. =head2 cells(\%args) Returns a list of Net::Google::Spreadsheets::Cell objects. Acceptable arguments are: =over 4 =item min-row =item max-row =item min-col =item max-col =item range =item return-empty =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html#CellParameters> for details. =head2 cell(\%args) Returns Net::Google::Spreadsheets::Cell object. Arguments are: =over 4 =item col =item row =back =head2 batchupdate_cell(@args) update multiple cells with a batch request. Pass a list of hash references containing: =over 4 =item col =item row =item input_value =back =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/t/02_spreadsheets.t b/t/02_spreadsheets.t index fdfa04b..a075493 100644 --- a/t/02_spreadsheets.t +++ b/t/02_spreadsheets.t @@ -1,47 +1,45 @@ -use t::Util title => 'test for Net::Google::Spreadsheets'; +use t::Util; use Test::More; -use Digest::MD5 qw(md5_hex); - ok my $service = service; { my @sheets = $service->spreadsheets; ok scalar @sheets; isa_ok $sheets[0], 'Net::Google::Spreadsheets::Spreadsheet'; ok $sheets[0]->title; ok $sheets[0]->key; ok $sheets[0]->etag; } { ok my $ss = spreadsheet; isa_ok $ss, 'Net::Google::Spreadsheets::Spreadsheet'; is $ss->title, $t::Util::SPREADSHEET_TITLE; like $ss->id, qr{^http://spreadsheets.google.com/feeds/spreadsheets/}; isa_ok $ss->author, 'XML::Atom::Person'; is $ss->author->email, config->{username}; my $key = $ss->key; ok length $key, 'key defined'; my $ss2 = $service->spreadsheet({key => $key}); ok $ss2; isa_ok $ss2, 'Net::Google::Spreadsheets::Spreadsheet'; is $ss2->key, $key; is $ss2->title, $t::Util::SPREADSHEET_TITLE; } { my @existing = map {$_->title} $service->spreadsheets; my $title; while (1) { - $title = md5_hex(time, $$, rand, @existing); + $title = 'spreadsheet created at '.scalar localtime; grep {$_ eq $title} @existing or last; } my $ss = $service->spreadsheet({title => $title}); is $ss, undef, "spreadsheet named '$title' shouldn't exit"; my @ss = $service->spreadsheets({title => $title}); is scalar @ss, 0; } done_testing; diff --git a/t/03_worksheet.t b/t/03_worksheet.t index 21c139c..3ff3ca8 100644 --- a/t/03_worksheet.t +++ b/t/03_worksheet.t @@ -1,69 +1,69 @@ -use t::Util title => 'test for Net::Google::Spreadsheets'; +use t::Util; use Test::More; ok my $spreadsheet = spreadsheet, 'getting spreadsheet'; { ok my @ws = $spreadsheet->worksheets, 'getting worksheet'; ok scalar @ws; isa_ok($ws[0], 'Net::Google::Spreadsheets::Worksheet'); } my $args = { title => 'new worksheet', row_count => 10, col_count => 3, }; { my $before = scalar $spreadsheet->worksheets; ok my $ws = $spreadsheet->add_worksheet($args), "adding worksheet named '$args->{title}'"; isa_ok $ws, 'Net::Google::Spreadsheets::Worksheet'; is $ws->title, $args->{title}, 'title is correct'; is $ws->row_count, $args->{row_count}, 'row_count is correct'; is $ws->col_count, $args->{col_count}, 'col_count is correct'; my @ws = $spreadsheet->worksheets; is scalar @ws, $before + 1; ok grep {$_->title eq $args->{title} } @ws; } { my $ws = $spreadsheet->worksheet({title => $args->{title}}); isa_ok $ws, 'Net::Google::Spreadsheets::Worksheet'; is $ws->title, $args->{title}; is $ws->row_count, $args->{row_count}; is $ws->col_count, $args->{col_count}; $args->{title} = "title changed"; ok $ws->title($args->{title}), "changing title to $args->{title}"; is $ws->title, $args->{title}; is $ws->atom->title, $args->{title}; for (1 .. 2) { my $col_count = $ws->col_count + 1; my $row_count = $ws->row_count + 1; is $ws->col_count($col_count), $col_count, "changing col_count to $col_count"; is $ws->atom->get($ws->gsns, 'colCount'), $col_count; is $ws->col_count, $col_count; is $ws->row_count($row_count), $row_count, "changing row_count to $row_count"; is $ws->atom->get($ws->gsns, 'rowCount'), $row_count; is $ws->row_count, $row_count; } } { my $ws = $spreadsheet->worksheet({title => $args->{title}}); my @before = $spreadsheet->worksheets; ok grep {$_->id eq $ws->id} @before; ok grep {$_->title eq $ws->title} @before; ok $ws->delete, 'deleting worksheet'; my @ws = $spreadsheet->worksheets; is scalar @ws, (scalar @before) - 1, '(worksheet count)--'; ok ! grep({$_->id eq $ws->id} @ws), 'id disappeared'; ok ! grep({$_->title eq $ws->title} @ws), 'title disappeared'; is $spreadsheet->worksheet({title => $args->{title}}), undef, "shouldn't be able to get the worksheet"; } done_testing; diff --git a/t/04_cell.t b/t/04_cell.t index 974cb7d..ead956c 100644 --- a/t/04_cell.t +++ b/t/04_cell.t @@ -1,79 +1,79 @@ -use t::Util title => 'test for Net::Google::Spreadsheets'; +use t::Util; use Test::More; ok my $ws = spreadsheet->add_worksheet, 'add worksheet'; { my $value = 'first cell value'; my $cell = $ws->cell({col => 1, row => 1}); isa_ok $cell, 'Net::Google::Spreadsheets::Cell'; my $previous = $cell->content; is $previous, ''; ok $cell->input_value($value); is $cell->content, $value; } { my $value = 'second cell value'; my @cells = $ws->batchupdate_cell( {row => 1, col => 1, input_value => $value} ); is scalar @cells, 1; isa_ok $cells[0], 'Net::Google::Spreadsheets::Cell'; is $cells[0]->content, $value; } { my $value1 = 'third cell value'; my $value2 = 'fourth cell value'; my $value3 = 'fifth cell value'; { my @cells = $ws->batchupdate_cell( {row => 1, col => 1, input_value => $value1}, {row => 1, col => 2, input_value => $value2}, {row => 2, col => 2, input_value => $value3}, ); is scalar @cells, 3; isa_ok $cells[0], 'Net::Google::Spreadsheets::Cell'; ok grep {$_->col == 1 && $_->row == 1 && $_->content eq $value1} @cells; ok grep {$_->col == 2 && $_->row == 1 && $_->content eq $value2} @cells; ok grep {$_->col == 2 && $_->row == 2 && $_->content eq $value3} @cells; } { my @cells = $ws->cells( { 'min-col' => 1, 'max-col' => 2, } ); is scalar @cells, 3; ok grep {$_->col == 1 && $_->row == 1 && $_->content eq $value1} @cells; ok grep {$_->col == 2 && $_->row == 1 && $_->content eq $value2} @cells; ok grep {$_->col == 2 && $_->row == 2 && $_->content eq $value3} @cells; } { my @cells = $ws->cells( { range => 'A1:B2' } ); is scalar @cells, 3; ok grep {$_->col == 1 && $_->row == 1 && $_->content eq $value1} @cells; ok grep {$_->col == 2 && $_->row == 1 && $_->content eq $value2} @cells; ok grep {$_->col == 2 && $_->row == 2 && $_->content eq $value3} @cells; } { my @cells = $ws->cells( { range => 'A1:B2', 'return-empty' => 'true' } ); is scalar @cells, 4; ok grep {$_->col == 1 && $_->row == 2 && $_->content eq ''} @cells; } } { my @cells = $ws->batchupdate_cell( {row => 1, col => 1, input_value => 100}, {row => 1, col => 2, input_value => 200}, {row => 1, col => 3, input_value => '=A1+B1'}, ); is scalar @cells, 3; isa_ok $cells[0], 'Net::Google::Spreadsheets::Cell'; my $result = $ws->cell({ row => 1, col => 3}); is $result->content, 300; } ok $ws->delete, 'delete worksheet'; done_testing; diff --git a/t/05_rows.t b/t/05_rows.t index 0f27b02..82c92fb 100644 --- a/t/05_rows.t +++ b/t/05_rows.t @@ -1,53 +1,53 @@ -use t::Util title => 'test for Net::Google::Spreadsheets'; +use t::Util; use Test::More; ok my $ws = spreadsheet->add_worksheet, 'add worksheet'; { is scalar $ws->rows, 0; $ws->batchupdate_cell( {col => 1, row => 1, input_value => 'name'}, {col => 2, row => 1, input_value => 'mail'}, {col => 3, row => 1, input_value => 'nick'}, ); is scalar $ws->rows, 0; my $value = { name => 'Nobuo Danjou', mail => '[email protected]', nick => 'lopnor', }; my $row = $ws->add_row($value); isa_ok $row, 'Net::Google::Spreadsheets::Row'; is_deeply $row->content, $value; is_deeply $row->param, $value; is $row->param('name'), $value->{name}; my $newval = {name => '檀上伸郎'}; is_deeply $row->param($newval), { %$value, %$newval, }; my $value2 = { name => 'Kazuhiro Osawa', nick => 'yappo', mail => '', }; $row->content($value2); is_deeply $row->content, $value2; is scalar $ws->rows, 1; ok $row->delete; is scalar $ws->rows, 0; } { $ws->add_row( { name => $_ } ) for qw(danjou lopnor soffritto); is scalar $ws->rows, 3; my $row = $ws->row({sq => 'name = "lopnor"'}); isa_ok $row, 'Net::Google::Spreadsheets::Row'; is_deeply $row->content, {name => 'lopnor', nick => '', mail => ''}; } ok $ws->delete, 'delete worksheet'; done_testing; diff --git a/t/06_error.t b/t/06_error.t index 5e1a656..ac65400 100644 --- a/t/06_error.t +++ b/t/06_error.t @@ -1,12 +1,65 @@ use strict; -use Test::More tests => 1; +use Test::More; use Test::Exception; +use Test::MockModule; +use Test::MockObject; +use LWP::UserAgent; use Net::Google::Spreadsheets; throws_ok { my $service = Net::Google::Spreadsheets->new( username => 'foo', password => 'bar', ); } qr{Net::Google::AuthSub login failed}; + +{ + my $res = Test::MockObject->new; + $res->mock(is_success => sub {return 1}); + $res->mock(auth => sub {return 'foobar'}); + my $auth = Test::MockModule->new('Net::Google::AuthSub'); + $auth->mock('login' => sub {return $res}); + + ok my $service = Net::Google::Spreadsheets->new( + username => 'foo', + password => 'bar', + ); + is $service->ua->auth, 'foobar'; + { + my $ua = Test::MockModule->new('LWP::UserAgent'); + $ua->mock('request' => sub {return HTTP::Response->new(302)}); + + throws_ok { + $service->spreadsheets; + } qr{302 Found}; + } + { + my $ua = Test::MockModule->new('LWP::UserAgent'); + $ua->mock('request' => sub {return HTTP::Response->parse(<<END)}); +200 OK +Content-Type: application/atom+xml +Content-Length: 1 + +1 +END + throws_ok { + $service->spreadsheets; + } qr{broken}; + } + { + my $ua = Test::MockModule->new('LWP::UserAgent'); + $ua->mock('request' => sub {return HTTP::Response->parse(<<END)}); +200 OK +Content-Type: text/html +Content-Length: 13 + +<html></html> +END + throws_ok { + $service->spreadsheets; + } qr{is not 'application/atom\+xml'}; + } +} + +done_testing; diff --git a/t/Util.pm b/t/Util.pm index d363ff3..1856ab9 100644 --- a/t/Util.pm +++ b/t/Util.pm @@ -1,124 +1,125 @@ package t::Util; use strict; use warnings; use utf8; use Test::More; use Net::Google::Spreadsheets; sub PIT_KEY { 'google.com' } our $SPREADSHEET_TITLE; my ( $config, $service, ); BEGIN { my $builder = Test::More->builder; binmode($builder->output, ':utf8'); binmode($builder->failure_output, ':utf8'); binmode($builder->todo_output, ':utf8'); } sub import { my ($class, %args) = @_; my $caller = caller; strict->import; warnings->import; utf8->import; - check_env(qw(TEST_NET_GOOGLE_SPREADSHEETS)) or exit; + check_env(qw( + TEST_NET_GOOGLE_SPREADSHEETS + TEST_NET_GOOGLE_SPREADSHEETS_TITLE + )) or exit; { no warnings; check_use(qw(Config::Pit)) or exit; } check_config(PIT_KEY) or exit; - if (my $title = $args{title}) { - $SPREADSHEET_TITLE = $title; - check_spreadsheet_exists({title => $title}) or exit; - } + $SPREADSHEET_TITLE = $ENV{TEST_NET_GOOGLE_SPREADSHEETS_TITLE}; + check_spreadsheet_exists({title => $SPREADSHEET_TITLE}) or exit; { no strict 'refs'; for (qw(config service spreadsheet)) { *{"$caller\::$_"} = \&{$_}; } } } sub check_env { my (@env) = @_; for (@env) { unless ($ENV{$_}) { plan skip_all => "set $_ to run this test"; return; } } return 1; } sub check_use { my (@module) = @_; for (@module) { eval "use $_"; if ($@) { plan skip_all => "this test needs $_"; return; } } 1; } sub check_config { my $key = shift; my $config = &config($key); unless ($config) { plan skip_all => "set username and password for $key via 'ppit set $key'"; return; } return $config; } sub check_spreadsheet_exists { my ($args) = @_; $args->{title} or return 1; my $service = &service or die; my $sheet = $service->spreadsheet({title => $args->{title}}); unless ($sheet) { plan skip_all => "spreadsheet named '$args->{title}' doesn't exist"; return; } return $sheet; } sub config { my $key = shift; return $config if $config; my $c = Config::Pit::get($key); unless ($c->{username} && $c->{password}) { return; } $config = $c; return $config; } sub service { return $service if $service; my $c = &config or return; my $s = Net::Google::Spreadsheets->new( { username => $c->{username}, password => $c->{password}, } ) or return; $service = $s; return $service; } sub spreadsheet { my $title = shift || $SPREADSHEET_TITLE; return service->spreadsheet({title => $title}); } 1;
lopnor/Net-Google-Spreadsheets
0a64ca1a2ca94f7a18987641bf63a325e3cea85f
changes to prepare for release
diff --git a/.shipit b/.shipit index 8731dce..4b4516a 100644 --- a/.shipit +++ b/.shipit @@ -1 +1,3 @@ steps = FindVersion, ChangeVersion, CheckChangeLog, DistTest, Commit, Tag, MakeDist, UploadCPAN +git.tagpattern = release-%v +git.push_to = origin diff --git a/Changes b/Changes index 12d9707..4d6bfd2 100644 --- a/Changes +++ b/Changes @@ -1,17 +1,17 @@ Revision history for Perl extension Net::Google::Spreadsheets -0.05_01 Sun Aug 02 21:44:50 2009 - - Fix attribute problem (thanks to Eric Celeste) +0.05 Sun Aug 15 09:47:50 2009 + - Fix Moose attribute problem #48627(thanks to Eric Celeste, IMALPASS) 0.04 Wed Apr 15 09:22:59 2009 - Updated POD (thanks to Mr. Grue) 0.03 Sun Apr 05 13:22:21 2009 - param method for Net::Google::Spreadsheets::Row (thanks to Mr. Grue) 0.02 Sat Apr 04 22:32:40 2009 - Crypt::SSLeay dependency - Better error message on login failure (thanks to Mr. Grue) 0.01 Tue Dec 16 23:52:25 2008 - original version diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index 25f2282..bfb4cef 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,266 +1,266 @@ package Net::Google::Spreadsheets; use Moose; -use 5.008; +use 5.008001; extends 'Net::Google::Spreadsheets::Base'; use Carp; use Net::Google::AuthSub; use Net::Google::Spreadsheets::UserAgent; use Net::Google::Spreadsheets::Spreadsheet; -our $VERSION = '0.05_01'; +our $VERSION = '0.05'; BEGIN { $XML::Atom::DefaultVersion = 1; } has +contents => ( is => 'ro', default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full' ); has +service => ( is => 'ro', default => sub {return $_[0]}, ); has source => ( isa => 'Str', is => 'ro', required => 1, default => sub { __PACKAGE__.'-'.$VERSION }, ); has username => ( isa => 'Str', is => 'ro', required => 1 ); has password => ( isa => 'Str', is => 'ro', required => 1 ); has ua => ( isa => 'Net::Google::Spreadsheets::UserAgent', is => 'ro', handles => [qw(request feed entry post put)], ); sub BUILD { my $self = shift; my $authsub = Net::Google::AuthSub->new( service => 'wise', source => $self->source, ); my $res = $authsub->login( $self->username, $self->password, ); unless ($res && $res->is_success) { croak 'Net::Google::AuthSub login failed'; } $self->{ua} = Net::Google::Spreadsheets::UserAgent->new( source => $self->source, auth => $res->auth, ); } sub spreadsheets { my ($self, $args) = @_; if ($args->{key}) { my $atom = eval {$self->entry($self->contents.'/'.$args->{key})}; $atom or return; return Net::Google::Spreadsheets::Spreadsheet->new( atom => $atom, service => $self, ); } else { my $cond = $args->{title} ? { title => $args->{title}, 'title-exact' => 'true' } : {}; my $feed = $self->feed( $self->contents, $cond, ); return grep { (!%$args && 1) || ($args->{title} && $_->title eq $args->{title}) } map { Net::Google::Spreadsheets::Spreadsheet->new( atom => $_, service => $self ) } $feed->entries; } } sub spreadsheet { my ($self, $args) = @_; return ($self->spreadsheets($args))[0]; } 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, {row => 1, col => 4, input_value => 'age'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', age => '33', } ); # fetch rows my @rows = $worksheet->rows; # or fetch rows with query @rows = $worksheet->rows({sq => 'age > 20'}); # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 4 =item username Username for Google. This should be full email address format like '[email protected]'. =item password Password corresponding to the username. =item source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 4 =item title title of the spreadsheet. =item title-exact whether title search should match exactly or not. =item key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
lopnor/Net-Google-Spreadsheets
a6b215e417cf5732b481bb9f163a139a98a168a5
refactored tests
diff --git a/MANIFEST b/MANIFEST index b1c7ce1..6dfffc9 100644 --- a/MANIFEST +++ b/MANIFEST @@ -1,42 +1,42 @@ Changes inc/Module/Install.pm inc/Module/Install/AuthorTests.pm inc/Module/Install/Base.pm inc/Module/Install/Can.pm inc/Module/Install/Fetch.pm inc/Module/Install/Include.pm inc/Module/Install/Makefile.pm inc/Module/Install/Metadata.pm inc/Module/Install/TestBase.pm inc/Module/Install/Win32.pm inc/Module/Install/WriteAll.pm inc/Spiffy.pm inc/Test/Base.pm inc/Test/Base/Filter.pm inc/Test/Builder.pm inc/Test/Builder/Module.pm inc/Test/Exception.pm inc/Test/More.pm lib/Net/Google/Spreadsheets.pm lib/Net/Google/Spreadsheets/Base.pm lib/Net/Google/Spreadsheets/Cell.pm lib/Net/Google/Spreadsheets/Row.pm lib/Net/Google/Spreadsheets/Spreadsheet.pm lib/Net/Google/Spreadsheets/UserAgent.pm lib/Net/Google/Spreadsheets/Worksheet.pm Makefile.PL MANIFEST This list of files META.yml README t/00_compile.t t/01_instanciate.t t/02_spreadsheets.t -t/03_spreadsheet.t -t/04_worksheet.t -t/05_cell.t -t/06_rows.t -t/07_error.t +t/03_worksheet.t +t/04_cell.t +t/05_rows.t +t/06_error.t +t/Util.pm xt/01_podspell.t xt/02_perlcritic.t xt/03_pod.t xt/perlcriticrc diff --git a/MANIFEST.SKIP b/MANIFEST.SKIP index dfa5eaf..f32e539 100644 --- a/MANIFEST.SKIP +++ b/MANIFEST.SKIP @@ -1,21 +1,22 @@ \bRCS\b \bCVS\b ^MANIFEST\. ^Makefile$ ~$ ^# \.old$ ^blib/ ^pm_to_blib ^MakeMaker-\d \.gz$ \.cvsignore +\.gitignore ^t/9\d_.*\.t ^t/perlcritic ^tools/ \.svn/ \.git/ ^[^/]+\.yaml$ ^[^/]+\.pl$ ^\.shipit$ ^cover_db/ diff --git a/t/01_instanciate.t b/t/01_instanciate.t index a612cbe..6fcf6f1 100644 --- a/t/01_instanciate.t +++ b/t/01_instanciate.t @@ -1,10 +1,7 @@ -use lib 't/lib'; -use Test::GoogleSpreadsheets::Util; -use Test::FITesque; +use t::Util; +use Test::More; -run_tests { - test { - ['Test::GoogleSpreadsheets::Fixture'], - ['check_instance'], - } -}; +ok my $service = service(); +isa_ok $service, 'Net::Google::Spreadsheets'; + +done_testing; diff --git a/t/02_spreadsheets.t b/t/02_spreadsheets.t index 6dee961..fdfa04b 100644 --- a/t/02_spreadsheets.t +++ b/t/02_spreadsheets.t @@ -1,13 +1,47 @@ -use lib 't/lib'; -use Test::GoogleSpreadsheets::Util - title => 'test for Net::Google::Spreadsheets'; -use Test::FITesque; - -run_tests { - test { - ['Test::GoogleSpreadsheets::Spreadsheet'], - ['get_spreadsheets'], - ['get_a_spreadsheet', 'test for Net::Google::Spreadsheets'], - ['get_nonexisting_spreadsheet'], +use t::Util title => 'test for Net::Google::Spreadsheets'; +use Test::More; + +use Digest::MD5 qw(md5_hex); + +ok my $service = service; + +{ + my @sheets = $service->spreadsheets; + ok scalar @sheets; + isa_ok $sheets[0], 'Net::Google::Spreadsheets::Spreadsheet'; + ok $sheets[0]->title; + ok $sheets[0]->key; + ok $sheets[0]->etag; +} + +{ + ok my $ss = spreadsheet; + isa_ok $ss, 'Net::Google::Spreadsheets::Spreadsheet'; + is $ss->title, $t::Util::SPREADSHEET_TITLE; + like $ss->id, qr{^http://spreadsheets.google.com/feeds/spreadsheets/}; + isa_ok $ss->author, 'XML::Atom::Person'; + is $ss->author->email, config->{username}; + my $key = $ss->key; + ok length $key, 'key defined'; + my $ss2 = $service->spreadsheet({key => $key}); + ok $ss2; + isa_ok $ss2, 'Net::Google::Spreadsheets::Spreadsheet'; + is $ss2->key, $key; + is $ss2->title, $t::Util::SPREADSHEET_TITLE; +} + +{ + my @existing = map {$_->title} $service->spreadsheets; + my $title; + while (1) { + $title = md5_hex(time, $$, rand, @existing); + grep {$_ eq $title} @existing or last; } -}; + + my $ss = $service->spreadsheet({title => $title}); + is $ss, undef, "spreadsheet named '$title' shouldn't exit"; + my @ss = $service->spreadsheets({title => $title}); + is scalar @ss, 0; +} + +done_testing; diff --git a/t/03_worksheet.t b/t/03_worksheet.t index b7f48c1..21c139c 100644 --- a/t/03_worksheet.t +++ b/t/03_worksheet.t @@ -1,27 +1,69 @@ -use lib 't/lib'; -use Test::GoogleSpreadsheets::Util - title => 'test for Net::Google::Spreadsheets'; -use Test::FITesque; +use t::Util title => 'test for Net::Google::Spreadsheets'; +use Test::More; + +ok my $spreadsheet = spreadsheet, 'getting spreadsheet'; + +{ + ok my @ws = $spreadsheet->worksheets, 'getting worksheet'; + ok scalar @ws; + isa_ok($ws[0], 'Net::Google::Spreadsheets::Worksheet'); +} my $args = { title => 'new worksheet', row_count => 10, col_count => 3, }; -my $args2 = { - title => 'foobar', -}; +{ + my $before = scalar $spreadsheet->worksheets; + + ok my $ws = $spreadsheet->add_worksheet($args), "adding worksheet named '$args->{title}'"; + isa_ok $ws, 'Net::Google::Spreadsheets::Worksheet'; + is $ws->title, $args->{title}, 'title is correct'; + is $ws->row_count, $args->{row_count}, 'row_count is correct'; + is $ws->col_count, $args->{col_count}, 'col_count is correct'; + + my @ws = $spreadsheet->worksheets; + is scalar @ws, $before + 1; + ok grep {$_->title eq $args->{title} } @ws; +} + +{ + my $ws = $spreadsheet->worksheet({title => $args->{title}}); + isa_ok $ws, 'Net::Google::Spreadsheets::Worksheet'; + is $ws->title, $args->{title}; + is $ws->row_count, $args->{row_count}; + is $ws->col_count, $args->{col_count}; + + $args->{title} = "title changed"; + ok $ws->title($args->{title}), "changing title to $args->{title}"; + is $ws->title, $args->{title}; + is $ws->atom->title, $args->{title}; -run_tests { - test { - ['Test::GoogleSpreadsheets::Worksheet', - {spreadsheet_title => 'test for Net::Google::Spreadsheets'} - ], - ['get_worksheets'], - ['add_worksheet', $args], - ['edit_title', {from => $args->{title}, to => $args2->{title}}], - ['edit_rowcount', {title => $args2->{title}}], - ['delete_worksheet', {title => $args2->{title}}], + for (1 .. 2) { + my $col_count = $ws->col_count + 1; + my $row_count = $ws->row_count + 1; + is $ws->col_count($col_count), $col_count, "changing col_count to $col_count"; + is $ws->atom->get($ws->gsns, 'colCount'), $col_count; + is $ws->col_count, $col_count; + is $ws->row_count($row_count), $row_count, "changing row_count to $row_count"; + is $ws->atom->get($ws->gsns, 'rowCount'), $row_count; + is $ws->row_count, $row_count; } } + +{ + my $ws = $spreadsheet->worksheet({title => $args->{title}}); + my @before = $spreadsheet->worksheets; + ok grep {$_->id eq $ws->id} @before; + ok grep {$_->title eq $ws->title} @before; + ok $ws->delete, 'deleting worksheet'; + my @ws = $spreadsheet->worksheets; + is scalar @ws, (scalar @before) - 1, '(worksheet count)--'; + ok ! grep({$_->id eq $ws->id} @ws), 'id disappeared'; + ok ! grep({$_->title eq $ws->title} @ws), 'title disappeared'; + is $spreadsheet->worksheet({title => $args->{title}}), undef, "shouldn't be able to get the worksheet"; +} + +done_testing; diff --git a/t/04_cell.t b/t/04_cell.t index a57c947..974cb7d 100644 --- a/t/04_cell.t +++ b/t/04_cell.t @@ -1,16 +1,79 @@ -use lib 't/lib'; -use Test::GoogleSpreadsheets::Util - title => 'test for Net::Google::Spreadsheets'; -use Test::FITesque; +use t::Util title => 'test for Net::Google::Spreadsheets'; +use Test::More; -run_tests { - test { - ['Test::GoogleSpreadsheets::Cell', - {spreadsheet_title => 'test for Net::Google::Spreadsheets'}], - ['edit_cell', {col => 1, row => 1, input_value => 'hogehoge'}], - ['batchupdate_cell', - {col => 1, row => 1, input_value => 'foobar'}, - ], - ['check_value', {col => 1, row => 1}, 'foobar'], +ok my $ws = spreadsheet->add_worksheet, 'add worksheet'; + +{ + my $value = 'first cell value'; + my $cell = $ws->cell({col => 1, row => 1}); + isa_ok $cell, 'Net::Google::Spreadsheets::Cell'; + my $previous = $cell->content; + is $previous, ''; + ok $cell->input_value($value); + is $cell->content, $value; +} +{ + my $value = 'second cell value'; + my @cells = $ws->batchupdate_cell( + {row => 1, col => 1, input_value => $value} + ); + is scalar @cells, 1; + isa_ok $cells[0], 'Net::Google::Spreadsheets::Cell'; + is $cells[0]->content, $value; +} +{ + my $value1 = 'third cell value'; + my $value2 = 'fourth cell value'; + my $value3 = 'fifth cell value'; + { + my @cells = $ws->batchupdate_cell( + {row => 1, col => 1, input_value => $value1}, + {row => 1, col => 2, input_value => $value2}, + {row => 2, col => 2, input_value => $value3}, + ); + is scalar @cells, 3; + isa_ok $cells[0], 'Net::Google::Spreadsheets::Cell'; + ok grep {$_->col == 1 && $_->row == 1 && $_->content eq $value1} @cells; + ok grep {$_->col == 2 && $_->row == 1 && $_->content eq $value2} @cells; + ok grep {$_->col == 2 && $_->row == 2 && $_->content eq $value3} @cells; + } + { + my @cells = $ws->cells( + { + 'min-col' => 1, + 'max-col' => 2, + } + ); + is scalar @cells, 3; + ok grep {$_->col == 1 && $_->row == 1 && $_->content eq $value1} @cells; + ok grep {$_->col == 2 && $_->row == 1 && $_->content eq $value2} @cells; + ok grep {$_->col == 2 && $_->row == 2 && $_->content eq $value3} @cells; + } + { + my @cells = $ws->cells( { range => 'A1:B2' } ); + is scalar @cells, 3; + ok grep {$_->col == 1 && $_->row == 1 && $_->content eq $value1} @cells; + ok grep {$_->col == 2 && $_->row == 1 && $_->content eq $value2} @cells; + ok grep {$_->col == 2 && $_->row == 2 && $_->content eq $value3} @cells; } -}; + { + my @cells = $ws->cells( { range => 'A1:B2', 'return-empty' => 'true' } ); + is scalar @cells, 4; + ok grep {$_->col == 1 && $_->row == 2 && $_->content eq ''} @cells; + } +} +{ + my @cells = $ws->batchupdate_cell( + {row => 1, col => 1, input_value => 100}, + {row => 1, col => 2, input_value => 200}, + {row => 1, col => 3, input_value => '=A1+B1'}, + ); + is scalar @cells, 3; + isa_ok $cells[0], 'Net::Google::Spreadsheets::Cell'; + my $result = $ws->cell({ row => 1, col => 3}); + is $result->content, 300; +} + +ok $ws->delete, 'delete worksheet'; + +done_testing; diff --git a/t/04_worksheet.t b/t/04_worksheet.t deleted file mode 100644 index b266fea..0000000 --- a/t/04_worksheet.t +++ /dev/null @@ -1,88 +0,0 @@ -use strict; -use Test::More; - -use Net::Google::Spreadsheets; - -my $ss; -BEGIN { - plan skip_all => 'set TEST_NET_GOOGLE_SPREADSHEETS to run this test' - unless $ENV{TEST_NET_GOOGLE_SPREADSHEETS}; - eval "use Config::Pit"; - plan skip_all => 'This Test needs Config::Pit.' if $@; - my $config = pit_get('google.com', require => { - 'username' => 'your username', - 'password' => 'your password', - } - ); - my $service = Net::Google::Spreadsheets->new( - username => $config->{username}, - password => $config->{password}, - ); - my $title = 'test for Net::Google::Spreadsheets'; - $ss = $service->spreadsheet({title => $title}); - plan skip_all => "test spreadsheet '$title' doesn't exist." unless $ss; - plan tests => 34; -} -{ - my @worksheets = $ss->worksheets; - ok scalar @worksheets; -} -{ - my $args = { - title => 'new worksheet', - row_count => 10, - col_count => 3, - }; - my $ws = $ss->add_worksheet($args); - isa_ok $ws, 'Net::Google::Spreadsheets::Worksheet'; - is $ws->title, $args->{title}; - is $ws->row_count, $args->{row_count}; - is $ws->col_count, $args->{col_count}; - my $ws2 = $ss->worksheet({title => $args->{title}}); - isa_ok $ws2, 'Net::Google::Spreadsheets::Worksheet'; - is $ws2->title, $args->{title}; - is $ws2->row_count, $args->{row_count}; - is $ws2->col_count, $args->{col_count}; - ok $ws2->delete; - ok ! grep {$_->id eq $ws->id} $ss->worksheets; - ok ! grep {$_->id eq $ws2->id} $ss->worksheets; -} -{ - my ($ws) = $ss->worksheets; - isa_ok $ws, 'Net::Google::Spreadsheets::Worksheet'; -} -{ - my $before = scalar $ss->worksheets; - my $ws = $ss->add_worksheet({title => 'new_worksheet'}); - isa_ok $ws, 'Net::Google::Spreadsheets::Worksheet'; - is scalar $ss->worksheets, $before + 1; - ok grep {$_->id eq $ws->id} $ss->worksheets; -} -{ - my $ws = ($ss->worksheets)[-1]; - my $title = $ws->title . '+add'; - is $ws->title($title), $title; - is $ws->atom->title, $title; - is $ws->title, $title; -} -{ - my $ws = ($ss->worksheets)[-1]; - for (1 .. 2) { - my $col_count = $ws->col_count + 1; - my $row_count = $ws->row_count + 1; - is $ws->col_count($col_count), $col_count; - is $ws->atom->get($ws->gsns, 'colCount'), $col_count; - is $ws->col_count, $col_count; - is $ws->row_count($row_count), $row_count; - is $ws->atom->get($ws->gsns, 'rowCount'), $row_count; - is $ws->row_count, $row_count; - } -} -{ - my $before = scalar $ss->worksheets; - my $ws = ($ss->worksheets)[-1]; - ok $ws->delete; - my @after = $ss->worksheets; - is scalar @after, $before - 1; - ok ! grep {$_->id eq $ws->id} @after; -} diff --git a/t/05_cell.t b/t/05_cell.t deleted file mode 100644 index ce3894f..0000000 --- a/t/05_cell.t +++ /dev/null @@ -1,99 +0,0 @@ -use strict; -use Test::More; - -use Net::Google::Spreadsheets; - -my $ws; -BEGIN { - plan skip_all => 'set TEST_NET_GOOGLE_SPREADSHEETS to run this test' - unless $ENV{TEST_NET_GOOGLE_SPREADSHEETS}; - eval "use Config::Pit"; - plan skip_all => 'This Test needs Config::Pit.' if $@; - my $config = pit_get('google.com', require => { - 'username' => 'your username', - 'password' => 'your password', - } - ); - my $service = Net::Google::Spreadsheets->new( - username => $config->{username}, - password => $config->{password}, - ); - my $title = 'test for Net::Google::Spreadsheets'; - my $ss = $service->spreadsheet({title => $title}); - plan skip_all => "test spreadsheet '$title' doesn't exist." unless $ss; - plan tests => 25; - $ws = $ss->add_worksheet; -} -{ - my $value = 'first cell value'; - my $cell = $ws->cell({col => 1, row => 1}); - isa_ok $cell, 'Net::Google::Spreadsheets::Cell'; - my $previous = $cell->content; - is $previous, ''; - ok $cell->input_value($value); - is $cell->content, $value; -} -{ - my $value = 'second cell value'; - my @cells = $ws->batchupdate_cell( - {row => 1, col => 1, input_value => $value} - ); - is scalar @cells, 1; - isa_ok $cells[0], 'Net::Google::Spreadsheets::Cell'; - is $cells[0]->content, $value; -} -{ - my $value1 = 'third cell value'; - my $value2 = 'fourth cell value'; - my $value3 = 'fifth cell value'; - { - my @cells = $ws->batchupdate_cell( - {row => 1, col => 1, input_value => $value1}, - {row => 1, col => 2, input_value => $value2}, - {row => 2, col => 2, input_value => $value3}, - ); - is scalar @cells, 3; - isa_ok $cells[0], 'Net::Google::Spreadsheets::Cell'; - ok grep {$_->col == 1 && $_->row == 1 && $_->content eq $value1} @cells; - ok grep {$_->col == 2 && $_->row == 1 && $_->content eq $value2} @cells; - ok grep {$_->col == 2 && $_->row == 2 && $_->content eq $value3} @cells; - } - { - my @cells = $ws->cells( - { - 'min-col' => 1, - 'max-col' => 2, - } - ); - is scalar @cells, 3; - ok grep {$_->col == 1 && $_->row == 1 && $_->content eq $value1} @cells; - ok grep {$_->col == 2 && $_->row == 1 && $_->content eq $value2} @cells; - ok grep {$_->col == 2 && $_->row == 2 && $_->content eq $value3} @cells; - } - { - my @cells = $ws->cells( { range => 'A1:B2' } ); - is scalar @cells, 3; - ok grep {$_->col == 1 && $_->row == 1 && $_->content eq $value1} @cells; - ok grep {$_->col == 2 && $_->row == 1 && $_->content eq $value2} @cells; - ok grep {$_->col == 2 && $_->row == 2 && $_->content eq $value3} @cells; - } - { - my @cells = $ws->cells( { range => 'A1:B2', 'return-empty' => 'true' } ); - is scalar @cells, 4; - ok grep {$_->col == 1 && $_->row == 2 && $_->content eq ''} @cells; - } -} -{ - my @cells = $ws->batchupdate_cell( - {row => 1, col => 1, input_value => 100}, - {row => 1, col => 2, input_value => 200}, - {row => 1, col => 3, input_value => '=A1+B1'}, - ); - is scalar @cells, 3; - isa_ok $cells[0], 'Net::Google::Spreadsheets::Cell'; - my $result = $ws->cell({ row => 1, col => 3}); - is $result->content, 300; -} -END { -# $ws->delete; -} diff --git a/t/06_rows.t b/t/05_rows.t similarity index 59% rename from t/06_rows.t rename to t/05_rows.t index a672140..0f27b02 100644 --- a/t/06_rows.t +++ b/t/05_rows.t @@ -1,73 +1,53 @@ -use strict; +use t::Util title => 'test for Net::Google::Spreadsheets'; use Test::More; -use utf8; -use Net::Google::Spreadsheets; +ok my $ws = spreadsheet->add_worksheet, 'add worksheet'; -my $ws; -BEGIN { - plan skip_all => 'set TEST_NET_GOOGLE_SPREADSHEETS to run this test' - unless $ENV{TEST_NET_GOOGLE_SPREADSHEETS}; - eval "use Config::Pit"; - plan skip_all => 'This Test needs Config::Pit.' if $@; - my $config = pit_get('google.com', require => { - 'username' => 'your username', - 'password' => 'your password', - } - ); - my $service = Net::Google::Spreadsheets->new( - username => $config->{username}, - password => $config->{password}, - ); - my $title = 'test for Net::Google::Spreadsheets'; - my $ss = $service->spreadsheet({title => $title}); - plan skip_all => "test spreadsheet '$title' doesn't exist." unless $ss; - plan tests => 14; - $ws = $ss->add_worksheet; -} { is scalar $ws->rows, 0; $ws->batchupdate_cell( {col => 1, row => 1, input_value => 'name'}, {col => 2, row => 1, input_value => 'mail'}, {col => 3, row => 1, input_value => 'nick'}, ); is scalar $ws->rows, 0; my $value = { name => 'Nobuo Danjou', mail => '[email protected]', nick => 'lopnor', }; my $row = $ws->add_row($value); isa_ok $row, 'Net::Google::Spreadsheets::Row'; is_deeply $row->content, $value; is_deeply $row->param, $value; is $row->param('name'), $value->{name}; my $newval = {name => '檀上伸郎'}; is_deeply $row->param($newval), { %$value, %$newval, }; my $value2 = { name => 'Kazuhiro Osawa', nick => 'yappo', mail => '', }; $row->content($value2); is_deeply $row->content, $value2; is scalar $ws->rows, 1; ok $row->delete; is scalar $ws->rows, 0; } + { $ws->add_row( { name => $_ } ) for qw(danjou lopnor soffritto); is scalar $ws->rows, 3; my $row = $ws->row({sq => 'name = "lopnor"'}); isa_ok $row, 'Net::Google::Spreadsheets::Row'; is_deeply $row->content, {name => 'lopnor', nick => '', mail => ''}; } -END { - $ws->delete; -} + +ok $ws->delete, 'delete worksheet'; + +done_testing; diff --git a/t/07_error.t b/t/06_error.t similarity index 100% rename from t/07_error.t rename to t/06_error.t diff --git a/t/lib/Test/GoogleSpreadsheets/Util.pm b/t/Util.pm similarity index 51% rename from t/lib/Test/GoogleSpreadsheets/Util.pm rename to t/Util.pm index 9cab681..d363ff3 100644 --- a/t/lib/Test/GoogleSpreadsheets/Util.pm +++ b/t/Util.pm @@ -1,86 +1,124 @@ -package Test::GoogleSpreadsheets::Util; +package t::Util; use strict; use warnings; use utf8; use Test::More; use Net::Google::Spreadsheets; +sub PIT_KEY { 'google.com' } + +our $SPREADSHEET_TITLE; +my ( + $config, + $service, +); + BEGIN { my $builder = Test::More->builder; binmode($builder->output, ':utf8'); binmode($builder->failure_output, ':utf8'); binmode($builder->todo_output, ':utf8'); } sub import { my ($class, %args) = @_; + my $caller = caller; strict->import; warnings->import; utf8->import; check_env(qw(TEST_NET_GOOGLE_SPREADSHEETS)) or exit; { no warnings; check_use(qw(Config::Pit)) or exit; } - my $config = check_config('google.com') or exit; - if (my $title = $args{spreadsheet_title}) { - check_spreadsheet_exists( - {title => $title, config => $config} - ) or exit; + check_config(PIT_KEY) or exit; + if (my $title = $args{title}) { + $SPREADSHEET_TITLE = $title; + check_spreadsheet_exists({title => $title}) or exit; + } + { + no strict 'refs'; + for (qw(config service spreadsheet)) { + *{"$caller\::$_"} = \&{$_}; + } } } sub check_env { my (@env) = @_; for (@env) { unless ($ENV{$_}) { plan skip_all => "set $_ to run this test"; return; } } return 1; } sub check_use { my (@module) = @_; for (@module) { eval "use $_"; if ($@) { plan skip_all => "this test needs $_"; return; } } 1; } sub check_config { - my ($key) = @_; - my $config = Config::Pit::get($key); - unless ($config->{username} && $config->{password}) { + my $key = shift; + my $config = &config($key); + unless ($config) { plan skip_all - => "set username and password for google.com via 'ppit set $key'"; + => "set username and password for $key via 'ppit set $key'"; return; } return $config; } sub check_spreadsheet_exists { my ($args) = @_; $args->{title} or return 1; - my $service = Net::Google::Spreadsheets->new( - { - username => $args->{config}->{username}, - password => $args->{config}->{password}, - } - ) or die; + my $service = &service or die; my $sheet = $service->spreadsheet({title => $args->{title}}); unless ($sheet) { plan skip_all => "spreadsheet named '$args->{title}' doesn't exist"; return; } return $sheet; } +sub config { + my $key = shift; + return $config if $config; + my $c = Config::Pit::get($key); + unless ($c->{username} && $c->{password}) { + return; + } + $config = $c; + return $config; +} + +sub service { + return $service if $service; + my $c = &config or return; + my $s = Net::Google::Spreadsheets->new( + { + username => $c->{username}, + password => $c->{password}, + } + ) or return; + $service = $s; + return $service; +} + +sub spreadsheet { + my $title = shift || $SPREADSHEET_TITLE; + return service->spreadsheet({title => $title}); +} + 1; diff --git a/t/lib/Test/GoogleSpreadsheets/Cell.pm b/t/lib/Test/GoogleSpreadsheets/Cell.pm deleted file mode 100644 index 253147e..0000000 --- a/t/lib/Test/GoogleSpreadsheets/Cell.pm +++ /dev/null @@ -1,40 +0,0 @@ -package Test::GoogleSpreadsheets::Cell; -use Moose; -use namespace::clean -except => 'meta'; -BEGIN {extends 'Test::GoogleSpreadsheets::Worksheet'}; -use Test::More; - -has worksheet => ( - is => 'ro', - isa => 'Net::Google::Spreadsheets::Worksheet', - required => 1, - lazy_build => 1, -); - -__PACKAGE__->meta->make_immutable; - -sub _build_worksheet { - my ($self) = @_; - return $self->spreadsheet->add_worksheet; -} - -sub edit_cell :Test :Plan(3) { - my ($self, $args) = @_; - my $cell = $self->worksheet->cell({col => $args->{col}, row => $args->{row}}); - isa_ok $cell, 'Net::Google::Spreadsheets::Cell'; - my $prev = $cell->content; - ok $cell->input_value($args->{input_value}); - is $cell->content, $args->{input_value}; -} - -sub batchupdate_cell { - my ($self, $args) = @_; - my @cells = $self->worksheet->batchupdate_cell($args); -} - -sub check_value :Test { - my ($self, $args, $content) = @_; - is $self->worksheet->cell($args)->content, $content; -} - -1; diff --git a/t/lib/Test/GoogleSpreadsheets/Fixture.pm b/t/lib/Test/GoogleSpreadsheets/Fixture.pm deleted file mode 100644 index 5890888..0000000 --- a/t/lib/Test/GoogleSpreadsheets/Fixture.pm +++ /dev/null @@ -1,18 +0,0 @@ -package Test::GoogleSpreadsheets::Fixture; -use Moose; -use namespace::clean -except => 'meta'; -use MooseX::NonMoose; -use Test::More; -use Digest::MD5 qw(md5_hex); - -BEGIN {extends 'Test::FITesque::Fixture'}; -with 'Test::GoogleSpreadsheets::Setup'; - -sub check_instance :Test { - my ($self) = @_; - isa_ok($self->service, 'Net::Google::Spreadsheets'); -} - -__PACKAGE__->meta->make_immutable; - -1; diff --git a/t/lib/Test/GoogleSpreadsheets/Setup.pm b/t/lib/Test/GoogleSpreadsheets/Setup.pm deleted file mode 100644 index fb21c28..0000000 --- a/t/lib/Test/GoogleSpreadsheets/Setup.pm +++ /dev/null @@ -1,34 +0,0 @@ -package Test::GoogleSpreadsheets::Setup; -use Moose::Role; -use Test::More; -use Net::Google::Spreadsheets; - -has service => ( - is => 'ro', - isa => 'Net::Google::Spreadsheets', - required => 1, - lazy_build => 1, -); - -has config => ( - is => 'ro', - isa => 'HashRef', - required => 1, - lazy_build => 1, -); - -sub _build_service { - my ($self) = @_; - return Net::Google::Spreadsheets->new( - username => $self->config->{username}, - password => $self->config->{password}, - ); -} - -sub _build_config { - my ($self, $key) = @_; - my $config = Config::Pit::get('google.com'); - return $config; -} - -1; diff --git a/t/lib/Test/GoogleSpreadsheets/Spreadsheet.pm b/t/lib/Test/GoogleSpreadsheets/Spreadsheet.pm deleted file mode 100644 index 50384b1..0000000 --- a/t/lib/Test/GoogleSpreadsheets/Spreadsheet.pm +++ /dev/null @@ -1,53 +0,0 @@ -package Test::GoogleSpreadsheets::Spreadsheet; -use Moose; -use namespace::clean -except => 'meta'; -use Test::More; -use Digest::MD5 qw(md5_hex); -BEGIN {extends 'Test::GoogleSpreadsheets::Fixture'}; - -sub get_spreadsheets :Test :Plan(5) { - my ($self) = @_; - my @sheets = $self->service->spreadsheets; - ok scalar @sheets; - isa_ok $sheets[0], 'Net::Google::Spreadsheets::Spreadsheet'; - ok $sheets[0]->title; - ok $sheets[0]->key; - ok $sheets[0]->etag; -} - -sub get_a_spreadsheet :Test :Plan(11) { - my ($self, $title) = @_; - ok(my $ss = $self->service->spreadsheet({title => $title})); - isa_ok $ss, 'Net::Google::Spreadsheets::Spreadsheet'; - is $ss->title, $title; - like $ss->id, qr{^http://spreadsheets.google.com/feeds/spreadsheets/}; - isa_ok $ss->author, 'XML::Atom::Person'; - is $ss->author->email, $self->config->{username}; - my $key = $ss->key; - ok length $key, 'key defined'; - my $ss2 = $self->service->spreadsheet({key => $key}); - ok $ss2; - isa_ok $ss2, 'Net::Google::Spreadsheets::Spreadsheet'; - is $ss2->key, $key; - is $ss2->title, $title; - return $ss; -} - -sub get_nonexisting_spreadsheet :Test :Plan(2) { - my ($self) = @_; - my @existing = map {$_->title} $self->service->spreadsheets; - my $title; - while (1) { - $title = md5_hex(time, $$, rand, @existing); - grep {$_ eq $title} @existing or last; - } - - my $ss = $self->service->spreadsheet({title => $title}); - is $ss, undef, "spreadsheet named '$title' shouldn't exit"; - my @ss = $self->service->spreadsheets({title => $title}); - is scalar @ss, 0; -} - -__PACKAGE__->meta->make_immutable; - -1; diff --git a/t/lib/Test/GoogleSpreadsheets/Worksheet.pm b/t/lib/Test/GoogleSpreadsheets/Worksheet.pm deleted file mode 100644 index f1c1c23..0000000 --- a/t/lib/Test/GoogleSpreadsheets/Worksheet.pm +++ /dev/null @@ -1,90 +0,0 @@ -package Test::GoogleSpreadsheets::Worksheet; -use Moose; -use namespace::clean -except => 'meta'; -BEGIN {extends 'Test::GoogleSpreadsheets::Fixture'}; -use Test::More; - -has spreadsheet_title => ( - is => 'ro', - isa => 'Str', - required => 1, -); - -has spreadsheet => ( - is => 'ro', - isa => 'Net::Google::Spreadsheets::Spreadsheet', - required => 1, - lazy_build => 1, -); - -sub _build_spreadsheet { - my ($self) = @_; - return $self->service->spreadsheet( {title => $self->spreadsheet_title} ); -} - -sub get_worksheets :Test :Plan(2) { - my ($self) = @_; - my @ws = $self->spreadsheet->worksheets; - ok scalar @ws; - isa_ok($ws[0], 'Net::Google::Spreadsheets::Worksheet'); -} - -sub add_worksheet :Test :Plan(10) { - my ($self, $args) = @_; - my $before = scalar $self->spreadsheet->worksheets; - - my $ws = $self->spreadsheet->add_worksheet($args); - isa_ok $ws, 'Net::Google::Spreadsheets::Worksheet'; - is $ws->title, $args->{title}; - is $ws->row_count, $args->{row_count}; - is $ws->col_count, $args->{col_count}; - - my @ws = $self->spreadsheet->worksheets; - is scalar @ws, $before + 1; - ok grep {$_->title eq $args->{title} } @ws; - - my $ws2 = $self->spreadsheet->worksheet({title => $args->{title}}); - isa_ok $ws2, 'Net::Google::Spreadsheets::Worksheet'; - is $ws2->title, $args->{title}; - is $ws2->row_count, $args->{row_count}; - is $ws2->col_count, $args->{col_count}; -} - -sub delete_worksheet :Test :Plan(4) { - my ($self, $args) = @_; - - my $before = scalar $self->spreadsheet->worksheets; - my $ws = $self->spreadsheet->worksheet($args); - ok $ws->delete; - my @ws = $self->spreadsheet->worksheets; - is scalar @ws, $before - 1; - ok ! grep {$_->id eq $ws->id} @ws; - ok ! grep {$_->id eq $ws->title} @ws; -} - -sub edit_title :Test :Plan(2) { - my ($self, $args) = @_; - my $ws = $self->spreadsheet->worksheet({title => $args->{from}}); - $ws->title($args->{to}); - is $ws->title, $args->{to}; - is $ws->atom->title, $args->{to}; -} - -sub edit_rowcount :Test :Plan(12) { - my ($self, $args) = @_; - my $ws = $self->spreadsheet->worksheet({title => $args->{title}}); - for (1 .. 2) { - my $col_count = $ws->col_count + 1; - my $row_count = $ws->row_count + 1; - is $ws->col_count($col_count), $col_count; - is $ws->atom->get($ws->gsns, 'colCount'), $col_count; - is $ws->col_count, $col_count; - is $ws->row_count($row_count), $row_count; - is $ws->atom->get($ws->gsns, 'rowCount'), $row_count; - is $ws->row_count, $row_count; - } -} - -__PACKAGE__->meta->make_immutable; - -1;
lopnor/Net-Google-Spreadsheets
cdca37f78858081e82b6f9e18231d627adb70654
Checking in changes prior to tagging of version 0.04. Changelog diff is:
diff --git a/Changes b/Changes index e127fa9..d41af4a 100644 --- a/Changes +++ b/Changes @@ -1,11 +1,14 @@ Revision history for Perl extension Net::Google::Spreadsheets +0.04 Wed Apr 15 09:22:59 2009 + - Updated POD (thanks to Mr. Grue) + 0.03 Sun Apr 05 13:22:21 2009 - param method for Net::Google::Spreadsheets::Row (thanks to Mr. Grue) 0.02 Sat Apr 04 22:32:40 2009 - Crypt::SSLeay dependency - Better error message on login failure (thanks to Mr. Grue) 0.01 Tue Dec 16 23:52:25 2008 - original version diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index 7f7dc08..d3ea69c 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,259 +1,265 @@ package Net::Google::Spreadsheets; use Moose; use 5.008; extends 'Net::Google::Spreadsheets::Base'; use Carp; use Net::Google::AuthSub; use Net::Google::Spreadsheets::UserAgent; use Net::Google::Spreadsheets::Spreadsheet; -our $VERSION = '0.03'; +our $VERSION = '0.04'; BEGIN { $XML::Atom::DefaultVersion = 1; } has +contents => ( is => 'ro', default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full' ); has +service => ( default => sub {return $_[0]} ); has source => ( isa => 'Str', is => 'ro', required => 1, default => sub { __PACKAGE__.'-'.$VERSION }, ); has username => ( isa => 'Str', is => 'ro', required => 1 ); has password => ( isa => 'Str', is => 'ro', required => 1 ); has ua => ( isa => 'Net::Google::Spreadsheets::UserAgent', is => 'ro', handles => [qw(request feed entry post put)], ); sub BUILD { my $self = shift; my $authsub = Net::Google::AuthSub->new( service => 'wise', source => $self->source, ); my $res = $authsub->login( $self->username, $self->password, ); unless ($res && $res->is_success) { croak 'Net::Google::AuthSub login failed'; } $self->{ua} = Net::Google::Spreadsheets::UserAgent->new( source => $self->source, auth => $res->auth, ); } sub spreadsheets { my ($self, $args) = @_; if ($args->{key}) { my $atom = eval {$self->entry($self->contents.'/'.$args->{key})}; $atom or return; return Net::Google::Spreadsheets::Spreadsheet->new( atom => $atom, service => $self, ); } else { my $cond = $args->{title} ? { title => $args->{title}, 'title-exact' => 'true' } : {}; my $feed = $self->feed( $self->contents, $cond, ); return grep { (!%$args && 1) || ($args->{title} && $_->title eq $args->{title}) } map { Net::Google::Spreadsheets::Spreadsheet->new( atom => $_, service => $self ) } $feed->entries; } } sub spreadsheet { my ($self, $args) = @_; return ($self->spreadsheets($args))[0]; } 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, + {row => 1, col => 4, input_value => 'age'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', + age => '33', } ); # fetch rows my @rows = $worksheet->rows; + # or fetch rows with query + + @rows = $worksheet->rows({sq => 'age > 20'}); + # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 4 =item username Username for Google. This should be full email address format like '[email protected]'. =item password Password corresponding to the username. =item source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 4 =item title title of the spreadsheet. =item title-exact whether title search should match exactly or not. =item key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Net/Google/Spreadsheets/Worksheet.pm b/lib/Net/Google/Spreadsheets/Worksheet.pm index c778125..3450adc 100644 --- a/lib/Net/Google/Spreadsheets/Worksheet.pm +++ b/lib/Net/Google/Spreadsheets/Worksheet.pm @@ -1,245 +1,250 @@ package Net::Google::Spreadsheets::Worksheet; use Moose; use Net::Google::Spreadsheets::Row; use Net::Google::Spreadsheets::Cell; extends 'Net::Google::Spreadsheets::Base'; has row_count => ( isa => 'Int', is => 'rw', default => 100, trigger => sub {$_[0]->update} ); has col_count => ( isa => 'Int', is => 'rw', default => 20, trigger => sub {$_[0]->update} ); has cellsfeed => ( isa => 'Str', is => 'ro', ); around entry => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->gsns, 'rowCount', $self->row_count); $entry->set($self->gsns, 'colCount', $self->col_count); return $entry; }; after _update_atom => sub { my ($self) = @_; $self->{content} = $self->atom->content->elem->getAttribute('src'); ($self->{cellsfeed}) = map {$_->href} grep { $_->rel eq 'http://schemas.google.com/spreadsheets/2006#cellsfeed' } $self->atom->link; $self->{row_count} = $self->atom->get($self->gsns, 'rowCount'); $self->{col_count} = $self->atom->get($self->gsns, 'colCount'); }; sub rows { my ($self, $cond) = @_; return $self->list_contents('Net::Google::Spreadsheets::Row', $cond); } sub row { my ($self, $cond) = @_; return ($self->rows($cond))[0]; } sub cells { my ($self, $cond) = @_; my $feed = $self->service->feed($self->cellsfeed, $cond); return map {Net::Google::Spreadsheets::Cell->new(container => $self, atom => $_)} $feed->entries; } sub cell { my ($self, $args) = @_; $self->cellsfeed or return; my $url = sprintf("%s/R%sC%s", $self->cellsfeed, $args->{row}, $args->{col}); return Net::Google::Spreadsheets::Cell->new( container => $self, atom => $self->service->entry($url), ); } sub batchupdate_cell { my ($self, @args) = @_; my $feed = XML::Atom::Feed->new; for ( @args ) { my $id = sprintf("%s/R%sC%s",$self->cellsfeed, $_->{row}, $_->{col}); $_->{id} = $_->{editurl} = $id; my $entry = Net::Google::Spreadsheets::Cell->new($_)->entry; $entry->set($self->batchns, operation => '', {type => 'update'}); $entry->set($self->batchns, id => $id); $feed->add_entry($entry); } my $res_feed = $self->service->post($self->cellsfeed."/batch", $feed, {'If-Match' => '*'}); $self->sync; return map { Net::Google::Spreadsheets::Cell->new( atom => $_, container => $self, ) } grep { my ($node) = $_->elem->getElementsByTagNameNS($self->batchns->{uri}, 'status'); $node->getAttribute('code') == 200; } $res_feed->entries; } sub add_row { my ($self, $args) = @_; my $entry = Net::Google::Spreadsheets::Row->new( content => $args, )->entry; my $atom = $self->service->post($self->content, $entry); $self->sync; return Net::Google::Spreadsheets::Row->new( container => $self, atom => $atom, ); } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Worksheet - Representation of worksheet. =head1 SYNOPSIS my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); my $ss = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); my $worksheet = $ss->worksheet({title => 'Sheet1'}); # update cell by batch request $worksheet->batchupdate_cell( {col => 1, row => 1, input_value => 'name'}, {col => 2, row => 1, input_value => 'nick'}, {col => 3, row => 1, input_value => 'mail'}, + {col => 4, row => 1, input_value => 'age'}, ); # get a cell object my $cell = $worksheet->cell({col => 1, row => 1}); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', + age => '33', } ); # get rows my @rows = $worksheet->rows; + # search rows + @rows = $worksheet->rows({sq => 'age > 20'}); + # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); =head1 METHODS =head2 rows(\%condition) Returns a list of Net::Google::Spreadsheets::Row objects. Acceptable arguments are: =over 4 =item sq Structured query on the full text in the worksheet. see the URL below for detail. =item orderby Set column name to use for ordering. =item reverse Set 'true' or 'false'. The default is 'false'. =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html#ListParameters> for details. =head2 row(\%condition) Returns first item of spreadsheets(\%condition) if available. =head2 cells(\%args) Returns a list of Net::Google::Spreadsheets::Cell objects. Acceptable arguments are: =over 4 =item min-row =item max-row =item min-col =item max-col =item range =item return-empty =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html#CellParameters> for details. =head2 cell(\%args) Returns Net::Google::Spreadsheets::Cell object. Arguments are: =over 4 =item col =item row =back =head2 batchupdate_cell(@args) update multiple cells with a batch request. Pass a list of hash references containing: =over 4 =item col =item row =item input_value =back =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut
lopnor/Net-Google-Spreadsheets
3c4f0db2848fbe3676822e02085d767f36f34c90
Checking in changes prior to tagging of version 0.03. Changelog diff is:
diff --git a/Changes b/Changes index afb353b..e127fa9 100644 --- a/Changes +++ b/Changes @@ -1,8 +1,11 @@ Revision history for Perl extension Net::Google::Spreadsheets +0.03 Sun Apr 05 13:22:21 2009 + - param method for Net::Google::Spreadsheets::Row (thanks to Mr. Grue) + 0.02 Sat Apr 04 22:32:40 2009 - Crypt::SSLeay dependency - - Better error message on login failure + - Better error message on login failure (thanks to Mr. Grue) 0.01 Tue Dec 16 23:52:25 2008 - original version diff --git a/MANIFEST.SKIP b/MANIFEST.SKIP index 27a635e..8137292 100644 --- a/MANIFEST.SKIP +++ b/MANIFEST.SKIP @@ -1,19 +1,20 @@ \bRCS\b \bCVS\b ^MANIFEST\. ^Makefile$ ~$ ^# \.old$ ^blib/ ^pm_to_blib ^MakeMaker-\d \.gz$ \.cvsignore ^t/9\d_.*\.t ^t/perlcritic ^tools/ \.svn/ ^[^/]+\.yaml$ ^[^/]+\.pl$ ^\.shipit$ +^cover_db/ diff --git a/Makefile.PL b/Makefile.PL index 304fe1a..afd098c 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,21 +1,21 @@ use inc::Module::Install; name 'Net-Google-Spreadsheets'; all_from 'lib/Net/Google/Spreadsheets.pm'; requires 'Carp'; requires 'XML::Atom'; requires 'Net::Google::AuthSub'; requires 'Crypt::SSLeay'; requires 'LWP::UserAgent'; requires 'URI'; -requires 'Moose'; +requires 'Moose' => 0.34; requires 'Path::Class'; tests 't/*.t'; author_tests 'xt'; build_requires 'Test::More'; build_requires 'Test::Exception'; use_test_base; auto_include; WriteAll; diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index 750bb69..7f7dc08 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,259 +1,259 @@ package Net::Google::Spreadsheets; use Moose; use 5.008; extends 'Net::Google::Spreadsheets::Base'; use Carp; use Net::Google::AuthSub; use Net::Google::Spreadsheets::UserAgent; use Net::Google::Spreadsheets::Spreadsheet; -our $VERSION = '0.02'; +our $VERSION = '0.03'; BEGIN { $XML::Atom::DefaultVersion = 1; } has +contents => ( is => 'ro', default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full' ); has +service => ( default => sub {return $_[0]} ); has source => ( isa => 'Str', is => 'ro', required => 1, default => sub { __PACKAGE__.'-'.$VERSION }, ); has username => ( isa => 'Str', is => 'ro', required => 1 ); has password => ( isa => 'Str', is => 'ro', required => 1 ); has ua => ( isa => 'Net::Google::Spreadsheets::UserAgent', is => 'ro', handles => [qw(request feed entry post put)], ); sub BUILD { my $self = shift; my $authsub = Net::Google::AuthSub->new( service => 'wise', source => $self->source, ); my $res = $authsub->login( $self->username, $self->password, ); unless ($res && $res->is_success) { croak 'Net::Google::AuthSub login failed'; } $self->{ua} = Net::Google::Spreadsheets::UserAgent->new( source => $self->source, auth => $res->auth, ); } sub spreadsheets { my ($self, $args) = @_; if ($args->{key}) { my $atom = eval {$self->entry($self->contents.'/'.$args->{key})}; $atom or return; return Net::Google::Spreadsheets::Spreadsheet->new( atom => $atom, service => $self, ); } else { my $cond = $args->{title} ? { title => $args->{title}, 'title-exact' => 'true' } : {}; my $feed = $self->feed( $self->contents, $cond, ); return grep { (!%$args && 1) || ($args->{title} && $_->title eq $args->{title}) } map { Net::Google::Spreadsheets::Spreadsheet->new( atom => $_, service => $self ) } $feed->entries; } } sub spreadsheet { my ($self, $args) = @_; return ($self->spreadsheets($args))[0]; } 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', } ); # fetch rows my @rows = $worksheet->rows; # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 4 =item username Username for Google. This should be full email address format like '[email protected]'. =item password Password corresponding to the username. =item source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 4 =item title title of the spreadsheet. =item title-exact whether title search should match exactly or not. =item key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
lopnor/Net-Google-Spreadsheets
d62fb800ee2f87a6c5a457662c6afac455cc4886
implemented $row->param
diff --git a/lib/Net/Google/Spreadsheets/Row.pm b/lib/Net/Google/Spreadsheets/Row.pm index 7bfc965..3941e13 100644 --- a/lib/Net/Google/Spreadsheets/Row.pm +++ b/lib/Net/Google/Spreadsheets/Row.pm @@ -1,96 +1,131 @@ package Net::Google::Spreadsheets::Row; use Moose; extends 'Net::Google::Spreadsheets::Base'; has +content => ( isa => 'HashRef', is => 'rw', default => sub { +{} }, - trigger => sub {$_[0]->update}, + trigger => sub { + $_[0]->update + }, ); after _update_atom => sub { my ($self) = @_; for my $node ($self->elem->getElementsByTagNameNS($self->gsxns->{uri}, '*')) { $self->{content}->{$node->localname} = $node->textContent; } }; around entry => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->{content}}) { $entry->set($self->gsxns, $key, $value); } return $entry; }; +sub param { + my ($self, $arg) = @_; + return $self->content unless $arg; + if (ref $arg && (ref $arg eq 'HASH')) { + return $self->content( + { + %{$self->content}, + %$arg, + } + ); + } else { + return $self->content->{$arg}; + } +} + 1; __END__ =head1 NAME Net::Google::Spreadsheets::Row - A representation class for Google Spreadsheet row. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword', ); # get a row my $row = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->row( { sq => 'id = 1000' } ); # get the content of a row my $hashref = $row->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $row->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); + # get and set values partially + + my $value = $row->param('name'); + # returns 'Nobuo Danjou' + + my $newval = $row->param({address => 'elsewhere'}); + # updates address (and keeps other fields) and returns new row value (with all fields) + + my $hashref = $row->param; + # same as $row->content; + +=head1 METHODS + +=head2 param + +sets and gets content value. + + =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/t/06_rows.t b/t/06_rows.t index befec26..a672140 100644 --- a/t/06_rows.t +++ b/t/06_rows.t @@ -1,62 +1,73 @@ use strict; use Test::More; +use utf8; use Net::Google::Spreadsheets; my $ws; BEGIN { plan skip_all => 'set TEST_NET_GOOGLE_SPREADSHEETS to run this test' unless $ENV{TEST_NET_GOOGLE_SPREADSHEETS}; eval "use Config::Pit"; plan skip_all => 'This Test needs Config::Pit.' if $@; my $config = pit_get('google.com', require => { 'username' => 'your username', 'password' => 'your password', } ); my $service = Net::Google::Spreadsheets->new( username => $config->{username}, password => $config->{password}, ); my $title = 'test for Net::Google::Spreadsheets'; my $ss = $service->spreadsheet({title => $title}); plan skip_all => "test spreadsheet '$title' doesn't exist." unless $ss; - plan tests => 11; + plan tests => 14; $ws = $ss->add_worksheet; } { is scalar $ws->rows, 0; $ws->batchupdate_cell( {col => 1, row => 1, input_value => 'name'}, {col => 2, row => 1, input_value => 'mail'}, {col => 3, row => 1, input_value => 'nick'}, ); is scalar $ws->rows, 0; my $value = { name => 'Nobuo Danjou', mail => '[email protected]', nick => 'lopnor', }; my $row = $ws->add_row($value); isa_ok $row, 'Net::Google::Spreadsheets::Row'; is_deeply $row->content, $value; + + is_deeply $row->param, $value; + is $row->param('name'), $value->{name}; + my $newval = {name => '檀上伸郎'}; + is_deeply $row->param($newval), { + %$value, + %$newval, + }; + my $value2 = { name => 'Kazuhiro Osawa', nick => 'yappo', + mail => '', }; $row->content($value2); is_deeply $row->content, $value2; is scalar $ws->rows, 1; ok $row->delete; is scalar $ws->rows, 0; } { $ws->add_row( { name => $_ } ) for qw(danjou lopnor soffritto); is scalar $ws->rows, 3; my $row = $ws->row({sq => 'name = "lopnor"'}); isa_ok $row, 'Net::Google::Spreadsheets::Row'; is_deeply $row->content, {name => 'lopnor', nick => '', mail => ''}; } END { $ws->delete; } diff --git a/xt/01_podspell.t b/xt/01_podspell.t index 19a3b1c..3bb585f 100644 --- a/xt/01_podspell.t +++ b/xt/01_podspell.t @@ -1,19 +1,20 @@ use Test::More; eval q{ use Test::Spelling }; plan skip_all => "Test::Spelling is not installed." if $@; add_stopwords(map { split /[\s\:\-]/ } <DATA>); $ENV{LANG} = 'C'; all_pod_files_spelling_ok('lib'); __DATA__ Nobuo Danjou [email protected] Net::Google::Spreadsheets API username google orderby UserAgent col min sq rewritable +param
lopnor/Net-Google-Spreadsheets
0e189e9edd9e875acb75511575312e3410c340a6
dependancy, better error message
diff --git a/Changes b/Changes index 4f2205e..afb353b 100644 --- a/Changes +++ b/Changes @@ -1,4 +1,8 @@ Revision history for Perl extension Net::Google::Spreadsheets +0.02 Sat Apr 04 22:32:40 2009 + - Crypt::SSLeay dependency + - Better error message on login failure + 0.01 Tue Dec 16 23:52:25 2008 - original version diff --git a/MANIFEST b/MANIFEST index b8bc906..b1c7ce1 100644 --- a/MANIFEST +++ b/MANIFEST @@ -1,40 +1,42 @@ Changes inc/Module/Install.pm inc/Module/Install/AuthorTests.pm inc/Module/Install/Base.pm inc/Module/Install/Can.pm inc/Module/Install/Fetch.pm inc/Module/Install/Include.pm inc/Module/Install/Makefile.pm inc/Module/Install/Metadata.pm inc/Module/Install/TestBase.pm inc/Module/Install/Win32.pm inc/Module/Install/WriteAll.pm inc/Spiffy.pm inc/Test/Base.pm inc/Test/Base/Filter.pm inc/Test/Builder.pm inc/Test/Builder/Module.pm +inc/Test/Exception.pm inc/Test/More.pm lib/Net/Google/Spreadsheets.pm lib/Net/Google/Spreadsheets/Base.pm lib/Net/Google/Spreadsheets/Cell.pm lib/Net/Google/Spreadsheets/Row.pm lib/Net/Google/Spreadsheets/Spreadsheet.pm lib/Net/Google/Spreadsheets/UserAgent.pm lib/Net/Google/Spreadsheets/Worksheet.pm Makefile.PL MANIFEST This list of files META.yml README t/00_compile.t t/01_instanciate.t t/02_spreadsheets.t t/03_spreadsheet.t t/04_worksheet.t t/05_cell.t t/06_rows.t +t/07_error.t xt/01_podspell.t xt/02_perlcritic.t xt/03_pod.t xt/perlcriticrc diff --git a/Makefile.PL b/Makefile.PL index cc56a26..304fe1a 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,19 +1,21 @@ use inc::Module::Install; name 'Net-Google-Spreadsheets'; all_from 'lib/Net/Google/Spreadsheets.pm'; requires 'Carp'; requires 'XML::Atom'; requires 'Net::Google::AuthSub'; +requires 'Crypt::SSLeay'; requires 'LWP::UserAgent'; requires 'URI'; requires 'Moose'; requires 'Path::Class'; tests 't/*.t'; author_tests 'xt'; build_requires 'Test::More'; +build_requires 'Test::Exception'; use_test_base; auto_include; WriteAll; diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index f6b8e1f..750bb69 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,258 +1,259 @@ package Net::Google::Spreadsheets; use Moose; use 5.008; extends 'Net::Google::Spreadsheets::Base'; use Carp; use Net::Google::AuthSub; use Net::Google::Spreadsheets::UserAgent; use Net::Google::Spreadsheets::Spreadsheet; -our $VERSION = '0.01'; +our $VERSION = '0.02'; BEGIN { $XML::Atom::DefaultVersion = 1; } has +contents => ( is => 'ro', default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full' ); has +service => ( default => sub {return $_[0]} ); has source => ( isa => 'Str', is => 'ro', required => 1, default => sub { __PACKAGE__.'-'.$VERSION }, ); has username => ( isa => 'Str', is => 'ro', required => 1 ); has password => ( isa => 'Str', is => 'ro', required => 1 ); has ua => ( isa => 'Net::Google::Spreadsheets::UserAgent', is => 'ro', - required => 1, - lazy => 1, - default => sub { - my ($self) = @_; - my $authsub = Net::Google::AuthSub->new( - service => 'wise', - source => $self->source, - ); - my $res = $authsub->login( - $self->username, - $self->password, - ); - $res->is_success or return; - Net::Google::Spreadsheets::UserAgent->new( - source => $self->source, - auth => $res->auth, - ); - }, handles => [qw(request feed entry post put)], ); +sub BUILD { + my $self = shift; + my $authsub = Net::Google::AuthSub->new( + service => 'wise', + source => $self->source, + ); + my $res = $authsub->login( + $self->username, + $self->password, + ); + unless ($res && $res->is_success) { + croak 'Net::Google::AuthSub login failed'; + } + $self->{ua} = Net::Google::Spreadsheets::UserAgent->new( + source => $self->source, + auth => $res->auth, + ); +} + sub spreadsheets { my ($self, $args) = @_; if ($args->{key}) { my $atom = eval {$self->entry($self->contents.'/'.$args->{key})}; $atom or return; return Net::Google::Spreadsheets::Spreadsheet->new( atom => $atom, service => $self, ); } else { my $cond = $args->{title} ? { title => $args->{title}, 'title-exact' => 'true' } : {}; my $feed = $self->feed( $self->contents, $cond, ); return grep { (!%$args && 1) || ($args->{title} && $_->title eq $args->{title}) } map { Net::Google::Spreadsheets::Spreadsheet->new( atom => $_, service => $self ) } $feed->entries; } } sub spreadsheet { my ($self, $args) = @_; return ($self->spreadsheets($args))[0]; } 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', } ); # fetch rows my @rows = $worksheet->rows; # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 4 =item username Username for Google. This should be full email address format like '[email protected]'. =item password Password corresponding to the username. =item source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 4 =item title title of the spreadsheet. =item title-exact whether title search should match exactly or not. =item key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Net/Google/Spreadsheets/Spreadsheet.pm b/lib/Net/Google/Spreadsheets/Spreadsheet.pm index 11fc5db..8a8431e 100644 --- a/lib/Net/Google/Spreadsheets/Spreadsheet.pm +++ b/lib/Net/Google/Spreadsheets/Spreadsheet.pm @@ -1,118 +1,118 @@ package Net::Google::Spreadsheets::Spreadsheet; use Moose; use Net::Google::Spreadsheets::Worksheet; use Path::Class; extends 'Net::Google::Spreadsheets::Base'; has +title => ( is => 'ro', ); has key => ( isa => 'Str', is => 'ro', required => 1, lazy => 1, default => sub { my $self = shift; my $key = file(URI->new($self->id)->path)->basename; return $key; } ); after _update_atom => sub { my ($self) = @_; $self->{content} = $self->atom->content->elem->getAttribute('src'); }; sub worksheet { my ($self, $cond) = @_; return ($self->worksheets($cond))[0]; } sub worksheets { my ($self, $cond) = @_; return $self->list_contents('Net::Google::Spreadsheets::Worksheet', $cond); } sub add_worksheet { my ($self, $args) = @_; - my $entry = Net::Google::Spreadsheets::Worksheet->new($args)->entry; + my $entry = Net::Google::Spreadsheets::Worksheet->new($args || {})->entry; my $atom = $self->service->post($self->content, $entry); $self->sync; return Net::Google::Spreadsheets::Worksheet->new( container => $self, atom => $atom, ); } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Spreadsheet - Representation of spreadsheet. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); =head1 METHODS =head2 worksheets(\%condition) Returns a list of Net::Google::Spreadsheets::Worksheet objects. Acceptable arguments are: =over 4 =item title =item title-exact =back =head2 worksheet(\%condition) Returns first item of worksheets(\%condition) if available. =head2 add_worksheet(\%attribuets) Creates new worksheet and returns a Net::Google::Spreadsheets::Worksheet object representing it. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/t/07_error.t b/t/07_error.t new file mode 100644 index 0000000..5e1a656 --- /dev/null +++ b/t/07_error.t @@ -0,0 +1,12 @@ +use strict; +use Test::More tests => 1; +use Test::Exception; + +use Net::Google::Spreadsheets; + +throws_ok { + my $service = Net::Google::Spreadsheets->new( + username => 'foo', + password => 'bar', + ); +} qr{Net::Google::AuthSub login failed}; diff --git a/xt/01_podspell.t b/xt/01_podspell.t index f003d9a..19a3b1c 100644 --- a/xt/01_podspell.t +++ b/xt/01_podspell.t @@ -1,15 +1,19 @@ use Test::More; eval q{ use Test::Spelling }; plan skip_all => "Test::Spelling is not installed." if $@; add_stopwords(map { split /[\s\:\-]/ } <DATA>); $ENV{LANG} = 'C'; all_pod_files_spelling_ok('lib'); __DATA__ Nobuo Danjou [email protected] Net::Google::Spreadsheets API username google orderby UserAgent +col +min +sq +rewritable
lopnor/Net-Google-Spreadsheets
13ec90a149eba0aa0db53934772d6d8b0315ef74
* fixed pods.
diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index 23ea368..f6b8e1f 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,258 +1,258 @@ package Net::Google::Spreadsheets; use Moose; use 5.008; extends 'Net::Google::Spreadsheets::Base'; use Carp; use Net::Google::AuthSub; use Net::Google::Spreadsheets::UserAgent; use Net::Google::Spreadsheets::Spreadsheet; our $VERSION = '0.01'; BEGIN { $XML::Atom::DefaultVersion = 1; } has +contents => ( is => 'ro', default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full' ); has +service => ( default => sub {return $_[0]} ); has source => ( isa => 'Str', is => 'ro', required => 1, default => sub { __PACKAGE__.'-'.$VERSION }, ); has username => ( isa => 'Str', is => 'ro', required => 1 ); has password => ( isa => 'Str', is => 'ro', required => 1 ); has ua => ( isa => 'Net::Google::Spreadsheets::UserAgent', is => 'ro', required => 1, lazy => 1, default => sub { my ($self) = @_; my $authsub = Net::Google::AuthSub->new( service => 'wise', source => $self->source, ); my $res = $authsub->login( $self->username, $self->password, ); $res->is_success or return; Net::Google::Spreadsheets::UserAgent->new( source => $self->source, auth => $res->auth, ); }, handles => [qw(request feed entry post put)], ); sub spreadsheets { my ($self, $args) = @_; if ($args->{key}) { my $atom = eval {$self->entry($self->contents.'/'.$args->{key})}; $atom or return; return Net::Google::Spreadsheets::Spreadsheet->new( atom => $atom, service => $self, ); } else { - my $cond = $args->{title} ? + my $cond = $args->{title} ? { title => $args->{title}, 'title-exact' => 'true' } : {}; my $feed = $self->feed( $self->contents, $cond, ); return grep { (!%$args && 1) || ($args->{title} && $_->title eq $args->{title}) } map { Net::Google::Spreadsheets::Spreadsheet->new( - atom => $_, + atom => $_, service => $self ) } $feed->entries; } } sub spreadsheet { my ($self, $args) = @_; return ($self->spreadsheets($args))[0]; } 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( - username => '[email protected]', + username => '[email protected]', password => 'mypassword' ); - + my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', } ); # fetch rows my @rows = $worksheet->rows; # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 4 =item username -Username for google. This should be full email address format like '[email protected]'. +Username for Google. This should be full email address format like '[email protected]'. =item password Password corresponding to the username. =item source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 4 =item title title of the spreadsheet. =item title-exact whether title search should match exactly or not. =item key key for the spreadsheet. You can get the key via the URL for the spreadsheet. http://spreadsheets.google.com/ccc?key=key =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets::Spreadsheet> L<Net::Google::Spreadsheets::Worksheet> L<Net::Google::Spreadsheets::Cell> L<Net::Google::Spreadsheets::Row> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Net/Google/Spreadsheets/Cell.pm b/lib/Net/Google/Spreadsheets/Cell.pm index 94095bc..58bf095 100644 --- a/lib/Net/Google/Spreadsheets/Cell.pm +++ b/lib/Net/Google/Spreadsheets/Cell.pm @@ -1,113 +1,113 @@ package Net::Google::Spreadsheets::Cell; use Moose; extends 'Net::Google::Spreadsheets::Base'; has row => ( isa => 'Int', is => 'ro', ); has col => ( isa => 'Int', is => 'ro', ); has input_value => ( isa => 'Str', is => 'rw', trigger => sub {$_[0]->update}, ); after _update_atom => sub { my ($self) = @_; my ($elem) = $self->elem->getElementsByTagNameNS($self->gsns->{uri}, 'cell'); $self->{row} = $elem->getAttribute('row'); $self->{col} = $elem->getAttribute('col'); $self->{input_value} = $elem->getAttribute('inputValue'); $self->{content} = $elem->textContent || ''; }; around entry => sub { my ($next, $self) = @_; my $entry = $next->($self); - $entry->set($self->gsns, 'cell', '', + $entry->set($self->gsns, 'cell', '', { row => $self->row, col => $self->col, inputValue => $self->input_value, } ); my $link = XML::Atom::Link->new; $link->rel('edit'); $link->type('application/atom+xml'); $link->href($self->editurl); $entry->link($link); $entry->id($self->id); return $entry; }; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Cell - A representation class for Google Spreadsheet cell. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( - username => '[email protected]', + username => '[email protected]', password => 'mypassword', ); # get a cell my $cell = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->cell( { col => 1, row => 1, } ); # update a cell $cell->input_value('new value'); # get the content of a cell my $value = $cell->content; =head1 ATTRIBUTES =head2 input_value Rewritable attribute. You can set formula like '=A1+B1' or so. =head2 content Read only attribute. You can get the result of formula. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Row.pm b/lib/Net/Google/Spreadsheets/Row.pm index 246d266..7bfc965 100644 --- a/lib/Net/Google/Spreadsheets/Row.pm +++ b/lib/Net/Google/Spreadsheets/Row.pm @@ -1,96 +1,96 @@ package Net::Google::Spreadsheets::Row; use Moose; extends 'Net::Google::Spreadsheets::Base'; has +content => ( isa => 'HashRef', is => 'rw', default => sub { +{} }, trigger => sub {$_[0]->update}, ); after _update_atom => sub { my ($self) = @_; for my $node ($self->elem->getElementsByTagNameNS($self->gsxns->{uri}, '*')) { $self->{content}->{$node->localname} = $node->textContent; } }; around entry => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->{content}}) { $entry->set($self->gsxns, $key, $value); } return $entry; }; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Row - A representation class for Google Spreadsheet row. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( - username => '[email protected]', + username => '[email protected]', password => 'mypassword', ); # get a row my $row = $service->spreadsheet( { title => 'list for new year cards', } )->worksheet( { title => 'Sheet1', } )->row( { sq => 'id = 1000' } ); # get the content of a row my $hashref = $row->content; my $id = $hashref->{id}; my $address = $hashref->{address}; # update a row $row->content( { id => 1000, address => 'somewhere', zip => '100-0001', name => 'Nobuo Danjou', } ); =head1 ATTRIBUTES =head2 content Rewritable attribute. You can get and set the value. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Spreadsheet.pm b/lib/Net/Google/Spreadsheets/Spreadsheet.pm index ecf3edb..11fc5db 100644 --- a/lib/Net/Google/Spreadsheets/Spreadsheet.pm +++ b/lib/Net/Google/Spreadsheets/Spreadsheet.pm @@ -1,118 +1,118 @@ package Net::Google::Spreadsheets::Spreadsheet; use Moose; use Net::Google::Spreadsheets::Worksheet; use Path::Class; extends 'Net::Google::Spreadsheets::Base'; has +title => ( is => 'ro', ); has key => ( isa => 'Str', is => 'ro', required => 1, lazy => 1, default => sub { my $self = shift; my $key = file(URI->new($self->id)->path)->basename; return $key; } ); after _update_atom => sub { my ($self) = @_; $self->{content} = $self->atom->content->elem->getAttribute('src'); }; sub worksheet { my ($self, $cond) = @_; return ($self->worksheets($cond))[0]; } sub worksheets { my ($self, $cond) = @_; return $self->list_contents('Net::Google::Spreadsheets::Worksheet', $cond); } sub add_worksheet { my ($self, $args) = @_; my $entry = Net::Google::Spreadsheets::Worksheet->new($args)->entry; my $atom = $self->service->post($self->content, $entry); $self->sync; return Net::Google::Spreadsheets::Worksheet->new( container => $self, atom => $atom, ); } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Spreadsheet - Representation of spreadsheet. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( - username => '[email protected]', + username => '[email protected]', password => 'mypassword' ); - + my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); =head1 METHODS =head2 worksheets(\%condition) Returns a list of Net::Google::Spreadsheets::Worksheet objects. Acceptable arguments are: =over 4 =item title =item title-exact =back =head2 worksheet(\%condition) Returns first item of worksheets(\%condition) if available. =head2 add_worksheet(\%attribuets) Creates new worksheet and returns a Net::Google::Spreadsheets::Worksheet object representing it. =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Worksheet.pm b/lib/Net/Google/Spreadsheets/Worksheet.pm index abf3bde..c778125 100644 --- a/lib/Net/Google/Spreadsheets/Worksheet.pm +++ b/lib/Net/Google/Spreadsheets/Worksheet.pm @@ -1,245 +1,245 @@ package Net::Google::Spreadsheets::Worksheet; use Moose; use Net::Google::Spreadsheets::Row; use Net::Google::Spreadsheets::Cell; extends 'Net::Google::Spreadsheets::Base'; has row_count => ( isa => 'Int', is => 'rw', default => 100, trigger => sub {$_[0]->update} ); has col_count => ( isa => 'Int', is => 'rw', default => 20, trigger => sub {$_[0]->update} ); has cellsfeed => ( isa => 'Str', is => 'ro', ); around entry => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->gsns, 'rowCount', $self->row_count); $entry->set($self->gsns, 'colCount', $self->col_count); return $entry; }; after _update_atom => sub { my ($self) = @_; $self->{content} = $self->atom->content->elem->getAttribute('src'); ($self->{cellsfeed}) = map {$_->href} grep { $_->rel eq 'http://schemas.google.com/spreadsheets/2006#cellsfeed' } $self->atom->link; $self->{row_count} = $self->atom->get($self->gsns, 'rowCount'); $self->{col_count} = $self->atom->get($self->gsns, 'colCount'); }; sub rows { my ($self, $cond) = @_; return $self->list_contents('Net::Google::Spreadsheets::Row', $cond); } sub row { my ($self, $cond) = @_; return ($self->rows($cond))[0]; } sub cells { my ($self, $cond) = @_; my $feed = $self->service->feed($self->cellsfeed, $cond); return map {Net::Google::Spreadsheets::Cell->new(container => $self, atom => $_)} $feed->entries; } sub cell { my ($self, $args) = @_; $self->cellsfeed or return; my $url = sprintf("%s/R%sC%s", $self->cellsfeed, $args->{row}, $args->{col}); return Net::Google::Spreadsheets::Cell->new( container => $self, atom => $self->service->entry($url), ); } sub batchupdate_cell { my ($self, @args) = @_; my $feed = XML::Atom::Feed->new; for ( @args ) { my $id = sprintf("%s/R%sC%s",$self->cellsfeed, $_->{row}, $_->{col}); $_->{id} = $_->{editurl} = $id; my $entry = Net::Google::Spreadsheets::Cell->new($_)->entry; $entry->set($self->batchns, operation => '', {type => 'update'}); $entry->set($self->batchns, id => $id); $feed->add_entry($entry); } my $res_feed = $self->service->post($self->cellsfeed."/batch", $feed, {'If-Match' => '*'}); $self->sync; - return map { + return map { Net::Google::Spreadsheets::Cell->new( atom => $_, container => $self, ) } grep { my ($node) = $_->elem->getElementsByTagNameNS($self->batchns->{uri}, 'status'); $node->getAttribute('code') == 200; } $res_feed->entries; } sub add_row { my ($self, $args) = @_; my $entry = Net::Google::Spreadsheets::Row->new( content => $args, )->entry; my $atom = $self->service->post($self->content, $entry); $self->sync; return Net::Google::Spreadsheets::Row->new( container => $self, atom => $atom, ); } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Worksheet - Representation of worksheet. =head1 SYNOPSIS my $service = Net::Google::Spreadsheets->new( - username => '[email protected]', + username => '[email protected]', password => 'mypassword', ); my $ss = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); my $worksheet = $ss->worksheet({title => 'Sheet1'}); # update cell by batch request $worksheet->batchupdate_cell( {col => 1, row => 1, input_value => 'name'}, {col => 2, row => 1, input_value => 'nick'}, {col => 3, row => 1, input_value => 'mail'}, ); # get a cell object my $cell = $worksheet->cell({col => 1, row => 1}); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', } ); # get rows my @rows = $worksheet->rows; # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); =head1 METHODS =head2 rows(\%condition) Returns a list of Net::Google::Spreadsheets::Row objects. Acceptable arguments are: =over 4 =item sq Structured query on the full text in the worksheet. see the URL below for detail. =item orderby Set column name to use for ordering. =item reverse Set 'true' or 'false'. The default is 'false'. =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html#ListParameters> for details. =head2 row(\%condition) Returns first item of spreadsheets(\%condition) if available. =head2 cells(\%args) Returns a list of Net::Google::Spreadsheets::Cell objects. Acceptable arguments are: =over 4 =item min-row =item max-row =item min-col =item max-col =item range =item return-empty =back See L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html#CellParameters> for details. =head2 cell(\%args) Returns Net::Google::Spreadsheets::Cell object. Arguments are: =over 4 =item col =item row =back =head2 batchupdate_cell(@args) update multiple cells with a batch request. Pass a list of hash references containing: =over 4 =item col =item row =item input_value =back =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut
lopnor/Net-Google-Spreadsheets
61dd51890ce1c454557b614d9708b6725e317269
pods and test for formula cell
diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index f730261..23ea368 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,247 +1,258 @@ package Net::Google::Spreadsheets; use Moose; use 5.008; extends 'Net::Google::Spreadsheets::Base'; use Carp; use Net::Google::AuthSub; use Net::Google::Spreadsheets::UserAgent; use Net::Google::Spreadsheets::Spreadsheet; our $VERSION = '0.01'; BEGIN { $XML::Atom::DefaultVersion = 1; } has +contents => ( is => 'ro', default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full' ); has +service => ( default => sub {return $_[0]} ); has source => ( isa => 'Str', is => 'ro', required => 1, default => sub { __PACKAGE__.'-'.$VERSION }, ); has username => ( isa => 'Str', is => 'ro', required => 1 ); has password => ( isa => 'Str', is => 'ro', required => 1 ); has ua => ( isa => 'Net::Google::Spreadsheets::UserAgent', is => 'ro', required => 1, lazy => 1, default => sub { my ($self) = @_; my $authsub = Net::Google::AuthSub->new( service => 'wise', source => $self->source, ); my $res = $authsub->login( $self->username, $self->password, ); $res->is_success or return; Net::Google::Spreadsheets::UserAgent->new( source => $self->source, auth => $res->auth, ); }, handles => [qw(request feed entry post put)], ); sub spreadsheets { my ($self, $args) = @_; if ($args->{key}) { my $atom = eval {$self->entry($self->contents.'/'.$args->{key})}; $atom or return; return Net::Google::Spreadsheets::Spreadsheet->new( atom => $atom, service => $self, ); } else { my $cond = $args->{title} ? { title => $args->{title}, 'title-exact' => 'true' } : {}; my $feed = $self->feed( $self->contents, $cond, ); return grep { (!%$args && 1) || ($args->{title} && $_->title eq $args->{title}) } map { Net::Google::Spreadsheets::Spreadsheet->new( atom => $_, service => $self ) } $feed->entries; } } sub spreadsheet { my ($self, $args) = @_; return ($self->spreadsheets($args))[0]; } 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, ); # get a cell my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', } ); # fetch rows my @rows = $worksheet->rows; # search a row my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 4 =item username Username for google. This should be full email address format like '[email protected]'. =item password Password corresponding to the username. =item source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 4 =item title title of the spreadsheet. =item title-exact whether title search should match exactly or not. +=item key + +key for the spreadsheet. You can get the key via the URL for the spreadsheet. +http://spreadsheets.google.com/ccc?key=key + =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> -L<Net::Google::Spreadsheets> +L<Net::Google::Spreadsheets::Spreadsheet> + +L<Net::Google::Spreadsheets::Worksheet> + +L<Net::Google::Spreadsheets::Cell> + +L<Net::Google::Spreadsheets::Row> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Net/Google/Spreadsheets/Cell.pm b/lib/Net/Google/Spreadsheets/Cell.pm index 88ac5cb..94095bc 100644 --- a/lib/Net/Google/Spreadsheets/Cell.pm +++ b/lib/Net/Google/Spreadsheets/Cell.pm @@ -1,74 +1,113 @@ package Net::Google::Spreadsheets::Cell; use Moose; extends 'Net::Google::Spreadsheets::Base'; has row => ( isa => 'Int', is => 'ro', ); has col => ( isa => 'Int', is => 'ro', ); has input_value => ( isa => 'Str', is => 'rw', trigger => sub {$_[0]->update}, ); after _update_atom => sub { my ($self) = @_; my ($elem) = $self->elem->getElementsByTagNameNS($self->gsns->{uri}, 'cell'); $self->{row} = $elem->getAttribute('row'); $self->{col} = $elem->getAttribute('col'); $self->{input_value} = $elem->getAttribute('inputValue'); $self->{content} = $elem->textContent || ''; }; around entry => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->gsns, 'cell', '', { row => $self->row, col => $self->col, inputValue => $self->input_value, } ); my $link = XML::Atom::Link->new; $link->rel('edit'); $link->type('application/atom+xml'); $link->href($self->editurl); $entry->link($link); $entry->id($self->id); return $entry; }; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Cell - A representation class for Google Spreadsheet cell. =head1 SYNOPSIS + use Net::Google::Spreadsheets; + + my $service = Net::Google::Spreadsheets->new( + username => '[email protected]', + password => 'mypassword', + ); + + # get a cell + my $cell = $service->spreadsheet( + { + title => 'list for new year cards', + } + )->worksheet( + { + title => 'Sheet1', + } + )->cell( + { + col => 1, + row => 1, + } + ); + + # update a cell + $cell->input_value('new value'); + + # get the content of a cell + my $value = $cell->content; + +=head1 ATTRIBUTES + +=head2 input_value + +Rewritable attribute. You can set formula like '=A1+B1' or so. + +=head2 content + +Read only attribute. You can get the result of formula. + =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Row.pm b/lib/Net/Google/Spreadsheets/Row.pm index 6aa226f..246d266 100644 --- a/lib/Net/Google/Spreadsheets/Row.pm +++ b/lib/Net/Google/Spreadsheets/Row.pm @@ -1,53 +1,96 @@ package Net::Google::Spreadsheets::Row; use Moose; extends 'Net::Google::Spreadsheets::Base'; has +content => ( isa => 'HashRef', is => 'rw', default => sub { +{} }, trigger => sub {$_[0]->update}, ); after _update_atom => sub { my ($self) = @_; for my $node ($self->elem->getElementsByTagNameNS($self->gsxns->{uri}, '*')) { $self->{content}->{$node->localname} = $node->textContent; } }; around entry => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->{content}}) { $entry->set($self->gsxns, $key, $value); } return $entry; }; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Row - A representation class for Google Spreadsheet row. =head1 SYNOPSIS + use Net::Google::Spreadsheets; + + my $service = Net::Google::Spreadsheets->new( + username => '[email protected]', + password => 'mypassword', + ); + + # get a row + my $row = $service->spreadsheet( + { + title => 'list for new year cards', + } + )->worksheet( + { + title => 'Sheet1', + } + )->row( + { + sq => 'id = 1000' + } + ); + + # get the content of a row + my $hashref = $row->content; + my $id = $hashref->{id}; + my $address = $hashref->{address}; + + # update a row + $row->content( + { + id => 1000, + address => 'somewhere', + zip => '100-0001', + name => 'Nobuo Danjou', + } + ); + +=head1 ATTRIBUTES + +=head2 content + +Rewritable attribute. You can get and set the value. + =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/t/05_cell.t b/t/05_cell.t index 29c53e2..7418a25 100644 --- a/t/05_cell.t +++ b/t/05_cell.t @@ -1,90 +1,101 @@ use strict; use Test::More; use Net::Google::Spreadsheets; my $ws; BEGIN { plan skip_all => 'set TEST_NET_GOOGLE_SPREADSHEETS to run this test' unless $ENV{TEST_NET_GOOGLE_SPREADSHEETS}; eval "use Config::Pit"; plan skip_all => 'This Test needs Config::Pit.' if $@; my $config = pit_get('google.com', require => { 'username' => 'your username', 'password' => 'your password', } ); my $service = Net::Google::Spreadsheets->new( username => $config->{username}, password => $config->{password}, ); my $title = 'test for Net::Google::Spreadsheets'; my $ss = $service->spreadsheet({title => $title}); plan skip_all => "test spreadsheet '$title' doesn't exist." unless $ss; - plan tests => 22; + plan tests => 25; $ws = $ss->add_worksheet; } { my $value = 'first cell value'; my $cell = $ws->cell({col => 1, row => 1}); isa_ok $cell, 'Net::Google::Spreadsheets::Cell'; my $previous = $cell->content; is $previous, ''; ok $cell->input_value($value); is $cell->content, $value; } { my $value = 'second cell value'; my @cells = $ws->batchupdate_cell( {row => 1, col => 1, input_value => $value} ); is scalar @cells, 1; isa_ok $cells[0], 'Net::Google::Spreadsheets::Cell'; is $cells[0]->content, $value; } { my $value1 = 'third cell value'; my $value2 = 'fourth cell value'; my $value3 = 'fifth cell value'; { my @cells = $ws->batchupdate_cell( {row => 1, col => 1, input_value => $value1}, {row => 1, col => 2, input_value => $value2}, {row => 2, col => 2, input_value => $value3}, ); is scalar @cells, 3; isa_ok $cells[0], 'Net::Google::Spreadsheets::Cell'; ok grep {$_->col == 1 && $_->row == 1 && $_->content eq $value1} @cells; ok grep {$_->col == 2 && $_->row == 1 && $_->content eq $value2} @cells; ok grep {$_->col == 2 && $_->row == 2 && $_->content eq $value3} @cells; } { my @cells = $ws->cells( { 'min-row' => 1, 'max-row' => 2, 'min-col' => 1, 'max-col' => 2, } ); is scalar @cells, 3; ok grep {$_->col == 1 && $_->row == 1 && $_->content eq $value1} @cells; ok grep {$_->col == 2 && $_->row == 1 && $_->content eq $value2} @cells; ok grep {$_->col == 2 && $_->row == 2 && $_->content eq $value3} @cells; } { my @cells = $ws->cells( { range => 'A1:B2' } ); is scalar @cells, 3; ok grep {$_->col == 1 && $_->row == 1 && $_->content eq $value1} @cells; ok grep {$_->col == 2 && $_->row == 1 && $_->content eq $value2} @cells; ok grep {$_->col == 2 && $_->row == 2 && $_->content eq $value3} @cells; } { my @cells = $ws->cells( { range => 'A1:B2', 'return-empty' => 'true' } ); is scalar @cells, 4; ok grep {$_->col == 1 && $_->row == 2 && $_->content eq ''} @cells; } } +{ + my @cells = $ws->batchupdate_cell( + {row => 1, col => 1, input_value => 100}, + {row => 1, col => 2, input_value => 200}, + {row => 1, col => 3, input_value => '=A1+B1'}, + ); + is scalar @cells, 3; + isa_ok $cells[0], 'Net::Google::Spreadsheets::Cell'; + my $result = $ws->cell({ row => 1, col => 3}); + is $result->content, 300; +} END { - $ws->delete; +# $ws->delete; }
lopnor/Net-Google-Spreadsheets
760c5aeb630730ffe8d25a2f68f8cee4b0988d2f
podspell
diff --git a/xt/01_podspell.t b/xt/01_podspell.t index 4f4f996..f003d9a 100644 --- a/xt/01_podspell.t +++ b/xt/01_podspell.t @@ -1,13 +1,15 @@ use Test::More; eval q{ use Test::Spelling }; plan skip_all => "Test::Spelling is not installed." if $@; add_stopwords(map { split /[\s\:\-]/ } <DATA>); $ENV{LANG} = 'C'; all_pod_files_spelling_ok('lib'); __DATA__ Nobuo Danjou [email protected] Net::Google::Spreadsheets API username google +orderby +UserAgent
lopnor/Net-Google-Spreadsheets
7a969a2847ec30c42b1bd86d6fd2e8eb31157b63
fix pod
diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index 5ae9026..f730261 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,246 +1,247 @@ package Net::Google::Spreadsheets; use Moose; use 5.008; extends 'Net::Google::Spreadsheets::Base'; use Carp; use Net::Google::AuthSub; use Net::Google::Spreadsheets::UserAgent; use Net::Google::Spreadsheets::Spreadsheet; our $VERSION = '0.01'; BEGIN { $XML::Atom::DefaultVersion = 1; } has +contents => ( is => 'ro', default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full' ); has +service => ( default => sub {return $_[0]} ); has source => ( isa => 'Str', is => 'ro', required => 1, default => sub { __PACKAGE__.'-'.$VERSION }, ); has username => ( isa => 'Str', is => 'ro', required => 1 ); has password => ( isa => 'Str', is => 'ro', required => 1 ); has ua => ( isa => 'Net::Google::Spreadsheets::UserAgent', is => 'ro', required => 1, lazy => 1, default => sub { my ($self) = @_; my $authsub = Net::Google::AuthSub->new( service => 'wise', source => $self->source, ); my $res = $authsub->login( $self->username, $self->password, ); $res->is_success or return; Net::Google::Spreadsheets::UserAgent->new( source => $self->source, auth => $res->auth, ); }, handles => [qw(request feed entry post put)], ); sub spreadsheets { my ($self, $args) = @_; if ($args->{key}) { my $atom = eval {$self->entry($self->contents.'/'.$args->{key})}; $atom or return; return Net::Google::Spreadsheets::Spreadsheet->new( atom => $atom, service => $self, ); } else { my $cond = $args->{title} ? { title => $args->{title}, 'title-exact' => 'true' } : {}; my $feed = $self->feed( $self->contents, $cond, ); return grep { (!%$args && 1) || ($args->{title} && $_->title eq $args->{title}) } map { Net::Google::Spreadsheets::Spreadsheet->new( atom => $_, service => $self ) } $feed->entries; } } sub spreadsheet { my ($self, $args) = @_; return ($self->spreadsheets($args))[0]; } 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'key_of_a_spreasheet' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {row => 1, col => 1, input_value => 'name'}, {row => 1, col => 2, input_value => 'nick'}, {row => 1, col => 3, input_value => 'mail'}, ); # get a cell - my $cell = $worksheet->cell(1,1); + my $cell = $worksheet->cell({col => 1, row => 1}); # update input value of a cell $cell->input_value('new value'); # add a row my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', } ); # fetch rows my @rows = $worksheet->rows; - my $row = $worksheet->row(1); + # search a row + my $row = $worksheet->row({sq => 'name = "Nobuo Danjou"'}); # update content of a row $row->content( { nick => 'lopnor', mail => '[email protected]', } ); =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 4 =item username Username for google. This should be full email address format like '[email protected]'. =item password Password corresponding to the username. =item source Source string to pass to Net::Google::AuthSub. =back =head2 spreadsheets(\%condition) returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 4 =item title title of the spreadsheet. =item title-exact whether title search should match exactly or not. =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/developers_guide_protocol.html> L<http://code.google.com/intl/en/apis/spreadsheets/docs/2.0/reference.html> L<Net::Google::AuthSub> L<Net::Google::Spreadsheets> =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
lopnor/Net-Google-Spreadsheets
acd7a13ea00bcbd9c530d1fc2d45529952eb98e3
fix pods
diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index 2bd8bab..3545cdc 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,215 +1,215 @@ package Net::Google::Spreadsheets; use Moose; use 5.008; extends 'Net::Google::Spreadsheets::Base'; use Carp; use Net::Google::AuthSub; use Net::Google::Spreadsheets::UserAgent; use Net::Google::Spreadsheets::Spreadsheet; our $VERSION = '0.01'; BEGIN { $XML::Atom::DefaultVersion = 1; } has contents => ( is => 'ro', default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full' ); has source => ( isa => 'Str', is => 'ro', required => 1, default => sub { __PACKAGE__.'-'.$VERSION }, ); has username => ( isa => 'Str', is => 'ro', required => 1 ); has password => ( isa => 'Str', is => 'ro', required => 1 ); has ua => ( isa => 'Net::Google::Spreadsheets::UserAgent', is => 'ro', required => 1, lazy => 1, default => sub { my ($self) = @_; my $authsub = Net::Google::AuthSub->new( service => 'wise', source => $self->source, ); my $res = $authsub->login( $self->username, $self->password, ); $res->is_success or return; Net::Google::Spreadsheets::UserAgent->new( source => $self->source, auth => $res->auth, ); }, handles => [qw(request feed entry post put)], ); sub spreadsheets { my ($self, $args) = @_; my $cond = $args->{title} ? { title => $args->{title}, 'title-exact' => 'true' } : {}; my $feed = $self->feed( $self->contents, $cond, ); return grep { (!%$args && 1) || ($args->{key} && $_->key eq $args->{key}) || ($args->{title} && $_->title eq $args->{title}) } map { Net::Google::Spreadsheets::Spreadsheet->new( atom => $_, service => $self ) } $feed->entries; } sub spreadsheet { my ($self, $args) = @_; return ($self->spreadsheets($args))[0]; } 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet( { key => 'pZV-pns_sm9PtH2WowhU2Ew' } ); # find a spreadsheet by title my $spreadsheet_by_title = $service->spreadsheet( { title => 'list for new year cards' } ); # find a worksheet by title my $worksheet = $spreadsheet->worksheet( { title => 'Sheet1' } ); # create a worksheet my $new_worksheet = $spreadsheet->add_worksheet( { title => 'Sheet2', row_count => 100, col_count => 3, } ); # update cell by batch request $worksheet->batchupdate_cell( {col => 1, row => 1, input_value => 'name'}, {col => 2, row => 1, input_value => 'nick'}, {col => 3, row => 1, input_value => 'mail'}, ); my $new_row = $worksheet->add_row( { name => 'Nobuo Danjou', nick => 'lopnor', mail => '[email protected]', } ); my @rows = $worksheet->rows; my $row = $worksheet->row(1); $row->content( { nick => 'lopnor', mail => '[email protected]', } ); =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 METHODS =head2 new Creates Google Spreadsheet API client. It takes arguments below: =over 4 =item username Username for google. This should be full email address format like '[email protected]'. =item password Password corresponding to the username. =back =head2 spreadsheets(\%condition) -returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arugments are: +returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arguments are: =over 4 =item title title of the spreadsheet. =item title-exact whether title search should match exactly or not. =back =head2 spreadsheet(\%condition) Returns first item of spreadsheets(\%condition) if available. =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/xt/01_podspell.t b/xt/01_podspell.t index e37cfef..4f4f996 100644 --- a/xt/01_podspell.t +++ b/xt/01_podspell.t @@ -1,11 +1,13 @@ use Test::More; eval q{ use Test::Spelling }; plan skip_all => "Test::Spelling is not installed." if $@; add_stopwords(map { split /[\s\:\-]/ } <DATA>); $ENV{LANG} = 'C'; all_pod_files_spelling_ok('lib'); __DATA__ Nobuo Danjou [email protected] Net::Google::Spreadsheets API +username +google
lopnor/Net-Google-Spreadsheets
aa55b8e22902cebad0ae22a7681ad49f54d97617
fix pod
diff --git a/MANIFEST b/MANIFEST index 37ef342..b8bc906 100644 --- a/MANIFEST +++ b/MANIFEST @@ -1,39 +1,40 @@ Changes inc/Module/Install.pm inc/Module/Install/AuthorTests.pm inc/Module/Install/Base.pm inc/Module/Install/Can.pm inc/Module/Install/Fetch.pm inc/Module/Install/Include.pm inc/Module/Install/Makefile.pm inc/Module/Install/Metadata.pm inc/Module/Install/TestBase.pm inc/Module/Install/Win32.pm inc/Module/Install/WriteAll.pm inc/Spiffy.pm inc/Test/Base.pm inc/Test/Base/Filter.pm inc/Test/Builder.pm inc/Test/Builder/Module.pm inc/Test/More.pm lib/Net/Google/Spreadsheets.pm lib/Net/Google/Spreadsheets/Base.pm lib/Net/Google/Spreadsheets/Cell.pm lib/Net/Google/Spreadsheets/Row.pm lib/Net/Google/Spreadsheets/Spreadsheet.pm +lib/Net/Google/Spreadsheets/UserAgent.pm lib/Net/Google/Spreadsheets/Worksheet.pm Makefile.PL MANIFEST This list of files META.yml README t/00_compile.t t/01_instanciate.t t/02_spreadsheets.t t/03_spreadsheet.t t/04_worksheet.t t/05_cell.t t/06_rows.t xt/01_podspell.t xt/02_perlcritic.t xt/03_pod.t xt/perlcriticrc diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index 28dfe57..2bd8bab 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,146 +1,215 @@ package Net::Google::Spreadsheets; use Moose; +use 5.008; extends 'Net::Google::Spreadsheets::Base'; use Carp; use Net::Google::AuthSub; use Net::Google::Spreadsheets::UserAgent; use Net::Google::Spreadsheets::Spreadsheet; our $VERSION = '0.01'; BEGIN { $XML::Atom::DefaultVersion = 1; } has contents => ( is => 'ro', default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full' ); has source => ( isa => 'Str', is => 'ro', required => 1, default => sub { __PACKAGE__.'-'.$VERSION }, ); has username => ( isa => 'Str', is => 'ro', required => 1 ); has password => ( isa => 'Str', is => 'ro', required => 1 ); has ua => ( isa => 'Net::Google::Spreadsheets::UserAgent', is => 'ro', required => 1, lazy => 1, default => sub { my ($self) = @_; my $authsub = Net::Google::AuthSub->new( service => 'wise', source => $self->source, ); my $res = $authsub->login( $self->username, $self->password, ); $res->is_success or return; Net::Google::Spreadsheets::UserAgent->new( source => $self->source, auth => $res->auth, ); }, handles => [qw(request feed entry post put)], ); sub spreadsheets { my ($self, $args) = @_; my $cond = $args->{title} ? { title => $args->{title}, 'title-exact' => 'true' } : {}; my $feed = $self->feed( $self->contents, - $cond + $cond, ); return grep { (!%$args && 1) || ($args->{key} && $_->key eq $args->{key}) || ($args->{title} && $_->title eq $args->{title}) } map { Net::Google::Spreadsheets::Spreadsheet->new( atom => $_, service => $self ) } $feed->entries; } sub spreadsheet { my ($self, $args) = @_; return ($self->spreadsheets($args))[0]; } 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key - my $spreadsheet = $service->spreadsheet({key => 'pZV-pns_sm9PtH2WowhU2Ew'}); + my $spreadsheet = $service->spreadsheet( + { + key => 'pZV-pns_sm9PtH2WowhU2Ew' + } + ); # find a spreadsheet by title - my $spreadsheet = $service->spreadsheet({title => 'list for new year cards'}); - my $worksheet = $spreadsheet->worksheet(1); + my $spreadsheet_by_title = $service->spreadsheet( + { + title => 'list for new year cards' + } + ); + + # find a worksheet by title + my $worksheet = $spreadsheet->worksheet( + { + title => 'Sheet1' + } + ); - my @fields = $worksheet->fields(); + # create a worksheet + my $new_worksheet = $spreadsheet->add_worksheet( + { + title => 'Sheet2', + row_count => 100, + col_count => 3, + } + ); - my $inserted_row = $worksheet->insert( + # update cell by batch request + $worksheet->batchupdate_cell( + {col => 1, row => 1, input_value => 'name'}, + {col => 2, row => 1, input_value => 'nick'}, + {col => 3, row => 1, input_value => 'mail'}, + ); + + my $new_row = $worksheet->add_row( { - name => 'danjou', + name => 'Nobuo Danjou', + nick => 'lopnor', + mail => '[email protected]', } ); my @rows = $worksheet->rows; my $row = $worksheet->row(1); - $row->update( + $row->content( { nick => 'lopnor', mail => '[email protected]', } ); =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. +=head1 METHODS + +=head2 new + +Creates Google Spreadsheet API client. It takes arguments below: + +=over 4 + +=item username + +Username for google. This should be full email address format like '[email protected]'. + +=item password + +Password corresponding to the username. + +=back + +=head2 spreadsheets(\%condition) + +returns list of Net::Google::Spreadsheets::Spreadsheet objects. Acceptable arugments are: + +=over 4 + +=item title + +title of the spreadsheet. + +=item title-exact + +whether title search should match exactly or not. + +=back + +=head2 spreadsheet(\%condition) + +Returns first item of spreadsheets(\%condition) if available. + =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Net/Google/Spreadsheets/UserAgent.pm b/lib/Net/Google/Spreadsheets/UserAgent.pm index 356debf..5f34f83 100644 --- a/lib/Net/Google/Spreadsheets/UserAgent.pm +++ b/lib/Net/Google/Spreadsheets/UserAgent.pm @@ -1,125 +1,125 @@ package Net::Google::Spreadsheets::UserAgent; use Moose; use Carp; use LWP::UserAgent; use HTTP::Request; use URI; use XML::Atom::Entry; use XML::Atom::Feed; has source => ( isa => 'Str', is => 'ro', required => 1, ); has auth => ( isa => 'Str', is => 'rw', required => 1, ); has ua => ( isa => 'LWP::UserAgent', is => 'ro', required => 1, lazy => 1, default => sub { my $self = shift; my $ua = LWP::UserAgent->new( agent => $self->source, ); $ua->default_headers( HTTP::Headers->new( Authorization => sprintf('GoogleLogin auth=%s', $self->auth), GData_Version => 2, ) ); return $ua; } ); sub request { my ($self, $args) = @_; my $method = delete $args->{method}; $method ||= $args->{content} ? 'POST' : 'GET'; my $uri = URI->new($args->{'uri'}); $uri->query_form($args->{query}) if $args->{query}; my $req = HTTP::Request->new($method => "$uri"); $req->content($args->{content}) if $args->{content}; $req->header('Content-Type' => $args->{content_type}) if $args->{content_type}; if ($args->{header}) { while (my @pair = each %{$args->{header}}) { $req->header(@pair); } } my $res = $self->ua->request($req); unless ($res->is_success) { # warn $res->request->as_string; # warn $res->as_string; - croak "request failed: ",$res->code; + die sprintf("request for '%s' failed: %s", $uri, $res->status_line); } return $res; } sub feed { my ($self, $url, $query) = @_; my $res = $self->request( { uri => $url, query => $query || undef, } ); return XML::Atom::Feed->new(\($res->content)); } sub entry { my ($self, $url, $query) = @_; my $res = $self->request( { uri => $url, query => $query || undef, } ); return XML::Atom::Entry->new(\($res->content)); } sub post { my ($self, $url, $entry, $header) = @_; my $res = $self->request( { uri => $url, content => $entry->as_xml, header => $header || undef, content_type => 'application/atom+xml', } ); return (ref $entry)->new(\($res->content)); } sub put { my ($self, $args) = @_; my $res = $self->request( { method => 'PUT', uri => $args->{self}->editurl, content => $args->{entry}->as_xml, header => {'If-Match' => $args->{self}->etag }, content_type => 'application/atom+xml', } ); return XML::Atom::Entry->new(\($res->content)); } 1; __END__ =head1 NAME Net::Google::Spreadsheets::UserAgent; =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Worksheet.pm b/lib/Net/Google/Spreadsheets/Worksheet.pm index 69c29f9..f4368a9 100644 --- a/lib/Net/Google/Spreadsheets/Worksheet.pm +++ b/lib/Net/Google/Spreadsheets/Worksheet.pm @@ -1,111 +1,116 @@ package Net::Google::Spreadsheets::Worksheet; use Moose; use Net::Google::Spreadsheets::Row; use Net::Google::Spreadsheets::Cell; extends 'Net::Google::Spreadsheets::Base'; has row_count => ( isa => 'Int', is => 'rw', default => 100, trigger => sub {$_[0]->update} ); has col_count => ( isa => 'Int', is => 'rw', default => 20, trigger => sub {$_[0]->update} ); has cellsfeed => ( isa => 'Str', is => 'ro', ); around entry => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->gsns, 'rowCount', $self->row_count); $entry->set($self->gsns, 'colCount', $self->col_count); return $entry; }; after _update_atom => sub { my ($self) = @_; $self->{content} = $self->atom->content->elem->getAttribute('src'); ($self->{cellsfeed}) = map {$_->href} grep { $_->rel eq 'http://schemas.google.com/spreadsheets/2006#cellsfeed' } $self->atom->link; $self->{row_count} = $self->atom->get($self->gsns, 'rowCount'); $self->{col_count} = $self->atom->get($self->gsns, 'colCount'); }; sub rows { my ($self, $cond) = @_; return $self->list_contents('Net::Google::Spreadsheets::Row', $cond); } +sub row { + my ($self, $cond) = @_; + return ($self->rows($cond))[0]; +} + sub cell { my ($self, $row, $col) = @_; $self->cellsfeed or return; my $url = sprintf("%s/R%sC%s", $self->cellsfeed, $row, $col); return Net::Google::Spreadsheets::Cell->new( container => $self, atom => $self->service->entry($url), ); } sub batchupdate_cell { my ($self, @args) = @_; my $feed = XML::Atom::Feed->new; for ( @args ) { my $id = sprintf("%s/R%sC%s",$self->cellsfeed, $_->{row}, $_->{col}); $_->{id} = $_->{editurl} = $id; my $entry = Net::Google::Spreadsheets::Cell->new($_)->entry; $entry->set($self->batchns, operation => '', {type => 'update'}); $entry->set($self->batchns, id => $id); $feed->add_entry($entry); } my $res_feed = $self->service->post($self->cellsfeed."/batch", $feed, {'If-Match' => '*'}); $self->sync; return map { Net::Google::Spreadsheets::Cell->new( atom => $_, container => $self, ) } grep { my ($node) = $_->elem->getElementsByTagNameNS($self->batchns->{uri}, 'status'); $node->getAttribute('code') == 200; } $res_feed->entries; } sub add_row { my ($self, $args) = @_; my $entry = Net::Google::Spreadsheets::Row->new( content => $args, )->entry; my $atom = $self->service->post($self->content, $entry); $self->sync; return Net::Google::Spreadsheets::Row->new( container => $self, atom => $atom, ); } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Worksheet - Representation of worksheet. =head1 SYNOPSIS =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/t/04_worksheet.t b/t/04_worksheet.t index 9f40ed8..b266fea 100644 --- a/t/04_worksheet.t +++ b/t/04_worksheet.t @@ -1,76 +1,88 @@ use strict; use Test::More; use Net::Google::Spreadsheets; my $ss; BEGIN { plan skip_all => 'set TEST_NET_GOOGLE_SPREADSHEETS to run this test' unless $ENV{TEST_NET_GOOGLE_SPREADSHEETS}; eval "use Config::Pit"; plan skip_all => 'This Test needs Config::Pit.' if $@; my $config = pit_get('google.com', require => { 'username' => 'your username', 'password' => 'your password', } ); my $service = Net::Google::Spreadsheets->new( username => $config->{username}, password => $config->{password}, ); my $title = 'test for Net::Google::Spreadsheets'; $ss = $service->spreadsheet({title => $title}); plan skip_all => "test spreadsheet '$title' doesn't exist." unless $ss; - plan tests => 27; + plan tests => 34; } { my @worksheets = $ss->worksheets; ok scalar @worksheets; } { - my $title = 'new worksheet'; - my $ws = $ss->add_worksheet({title => $title}); + my $args = { + title => 'new worksheet', + row_count => 10, + col_count => 3, + }; + my $ws = $ss->add_worksheet($args); isa_ok $ws, 'Net::Google::Spreadsheets::Worksheet'; - is $ws->title, $title; - my $ws2 = $ss->worksheet({title => $title}); + is $ws->title, $args->{title}; + is $ws->row_count, $args->{row_count}; + is $ws->col_count, $args->{col_count}; + my $ws2 = $ss->worksheet({title => $args->{title}}); isa_ok $ws2, 'Net::Google::Spreadsheets::Worksheet'; - is $ws2->title, $title; + is $ws2->title, $args->{title}; + is $ws2->row_count, $args->{row_count}; + is $ws2->col_count, $args->{col_count}; + ok $ws2->delete; + ok ! grep {$_->id eq $ws->id} $ss->worksheets; + ok ! grep {$_->id eq $ws2->id} $ss->worksheets; } { my ($ws) = $ss->worksheets; isa_ok $ws, 'Net::Google::Spreadsheets::Worksheet'; } { my $before = scalar $ss->worksheets; - my $ws = $ss->add_worksheet; + my $ws = $ss->add_worksheet({title => 'new_worksheet'}); isa_ok $ws, 'Net::Google::Spreadsheets::Worksheet'; is scalar $ss->worksheets, $before + 1; ok grep {$_->id eq $ws->id} $ss->worksheets; } { my $ws = ($ss->worksheets)[-1]; my $title = $ws->title . '+add'; is $ws->title($title), $title; is $ws->atom->title, $title; is $ws->title, $title; } { my $ws = ($ss->worksheets)[-1]; for (1 .. 2) { my $col_count = $ws->col_count + 1; my $row_count = $ws->row_count + 1; is $ws->col_count($col_count), $col_count; is $ws->atom->get($ws->gsns, 'colCount'), $col_count; is $ws->col_count, $col_count; is $ws->row_count($row_count), $row_count; is $ws->atom->get($ws->gsns, 'rowCount'), $row_count; is $ws->row_count, $row_count; } } { my $before = scalar $ss->worksheets; my $ws = ($ss->worksheets)[-1]; ok $ws->delete; - is scalar $ss->worksheets, $before - 1; - ok ! grep {$_ == $ws} $ss->worksheets; + my @after = $ss->worksheets; + is scalar @after, $before - 1; + ok ! grep {$_->id eq $ws->id} @after; }
lopnor/Net-Google-Spreadsheets
5c518a8972805539dc60d6a0bf8ac035e8762592
extract UserAgent from Spreadsheets
diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index 7539bad..28dfe57 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,239 +1,146 @@ package Net::Google::Spreadsheets; use Moose; extends 'Net::Google::Spreadsheets::Base'; use Carp; use Net::Google::AuthSub; +use Net::Google::Spreadsheets::UserAgent; use Net::Google::Spreadsheets::Spreadsheet; -use LWP::UserAgent; -use XML::Atom; -use XML::Atom::Feed; -use URI; -use HTTP::Headers; our $VERSION = '0.01'; BEGIN { $XML::Atom::DefaultVersion = 1; } has contents => ( is => 'ro', default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full' ); -has username => ( isa => 'Str', is => 'ro', required => 1 ); -has password => ( isa => 'Str', is => 'ro', required => 1 ); - has source => ( isa => 'Str', is => 'ro', required => 1, default => sub { __PACKAGE__.'-'.$VERSION }, ); -has auth => ( - isa => 'Str', - is => 'rw', +has username => ( isa => 'Str', is => 'ro', required => 1 ); +has password => ( isa => 'Str', is => 'ro', required => 1 ); + +has ua => ( + isa => 'Net::Google::Spreadsheets::UserAgent', + is => 'ro', required => 1, lazy => 1, default => sub { - my $self = shift; + my ($self) = @_; my $authsub = Net::Google::AuthSub->new( service => 'wise', source => $self->source, ); my $res = $authsub->login( $self->username, $self->password, ); $res->is_success or return; - return $res->auth; - }, -); - -has ua => ( - isa => 'LWP::UserAgent', - is => 'ro', - required => 1, - lazy => 1, - default => sub { - my $self = shift; - my $ua = LWP::UserAgent->new( - agent => $self->source, - ); - $ua->default_headers( - HTTP::Headers->new( - Authorization => sprintf('GoogleLogin auth=%s', $self->auth), - GData_Version => 2, - ) + Net::Google::Spreadsheets::UserAgent->new( + source => $self->source, + auth => $res->auth, ); - return $ua; - } + }, + handles => [qw(request feed entry post put)], ); sub spreadsheets { my ($self, $args) = @_; my $cond = $args->{title} ? { title => $args->{title}, 'title-exact' => 'true' } : {}; my $feed = $self->feed( $self->contents, $cond ); return grep { (!%$args && 1) || ($args->{key} && $_->key eq $args->{key}) || ($args->{title} && $_->title eq $args->{title}) } map { Net::Google::Spreadsheets::Spreadsheet->new( atom => $_, service => $self ) } $feed->entries; } sub spreadsheet { my ($self, $args) = @_; return ($self->spreadsheets($args))[0]; } -sub request { - my ($self, $args) = @_; - my $method = delete $args->{method}; - $method ||= $args->{content} ? 'POST' : 'GET'; - my $uri = URI->new($args->{'uri'}); - $uri->query_form($args->{query}) if $args->{query}; - my $req = HTTP::Request->new($method => "$uri"); - $req->content($args->{content}) if $args->{content}; - $req->header('Content-Type' => $args->{content_type}) if $args->{content_type}; - if ($args->{header}) { - while (my @pair = each %{$args->{header}}) { - $req->header(@pair); - } - } - my $res = $self->ua->request($req); - unless ($res->is_success) { -# warn $res->request->as_string; -# warn $res->as_string; - croak "request failed: ",$res->code; - } - return $res; -} - -sub feed { - my ($self, $url, $query) = @_; - my $res = $self->request( - { - uri => $url, - query => $query || undef, - } - ); - return XML::Atom::Feed->new(\($res->content)); -} - -sub entry { - my ($self, $url, $query) = @_; - my $res = $self->request( - { - uri => $url, - query => $query || undef, - } - ); - return XML::Atom::Entry->new(\($res->content)); -} - -sub post { - my ($self, $url, $entry, $header) = @_; - my $res = $self->request( - { - uri => $url, - content => $entry->as_xml, - header => $header || undef, - content_type => 'application/atom+xml', - } - ); - return (ref $entry)->new(\($res->content)); -# return XML::Atom::Entry->new(\($res->content)); -} - -sub put { - my ($self, $args) = @_; - my $res = $self->request( - { - method => 'PUT', - uri => $args->{self}->editurl, - content => $args->{entry}->as_xml, - header => {'If-Match' => $args->{self}->etag }, - content_type => 'application/atom+xml', - } - ); - return XML::Atom::Entry->new(\($res->content)); -} - 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); # find a spreadsheet by key my $spreadsheet = $service->spreadsheet({key => 'pZV-pns_sm9PtH2WowhU2Ew'}); # find a spreadsheet by title my $spreadsheet = $service->spreadsheet({title => 'list for new year cards'}); my $worksheet = $spreadsheet->worksheet(1); my @fields = $worksheet->fields(); my $inserted_row = $worksheet->insert( { name => 'danjou', } ); my @rows = $worksheet->rows; my $row = $worksheet->row(1); $row->update( { nick => 'lopnor', mail => '[email protected]', } ); =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Net/Google/Spreadsheets/UserAgent.pm b/lib/Net/Google/Spreadsheets/UserAgent.pm new file mode 100644 index 0000000..356debf --- /dev/null +++ b/lib/Net/Google/Spreadsheets/UserAgent.pm @@ -0,0 +1,125 @@ +package Net::Google::Spreadsheets::UserAgent; +use Moose; +use Carp; +use LWP::UserAgent; +use HTTP::Request; +use URI; +use XML::Atom::Entry; +use XML::Atom::Feed; + +has source => ( + isa => 'Str', + is => 'ro', + required => 1, +); + +has auth => ( + isa => 'Str', + is => 'rw', + required => 1, +); + +has ua => ( + isa => 'LWP::UserAgent', + is => 'ro', + required => 1, + lazy => 1, + default => sub { + my $self = shift; + my $ua = LWP::UserAgent->new( + agent => $self->source, + ); + $ua->default_headers( + HTTP::Headers->new( + Authorization => sprintf('GoogleLogin auth=%s', $self->auth), + GData_Version => 2, + ) + ); + return $ua; + } +); + +sub request { + my ($self, $args) = @_; + my $method = delete $args->{method}; + $method ||= $args->{content} ? 'POST' : 'GET'; + my $uri = URI->new($args->{'uri'}); + $uri->query_form($args->{query}) if $args->{query}; + my $req = HTTP::Request->new($method => "$uri"); + $req->content($args->{content}) if $args->{content}; + $req->header('Content-Type' => $args->{content_type}) if $args->{content_type}; + if ($args->{header}) { + while (my @pair = each %{$args->{header}}) { + $req->header(@pair); + } + } + my $res = $self->ua->request($req); + unless ($res->is_success) { +# warn $res->request->as_string; +# warn $res->as_string; + croak "request failed: ",$res->code; + } + return $res; +} + +sub feed { + my ($self, $url, $query) = @_; + my $res = $self->request( + { + uri => $url, + query => $query || undef, + } + ); + return XML::Atom::Feed->new(\($res->content)); +} + +sub entry { + my ($self, $url, $query) = @_; + my $res = $self->request( + { + uri => $url, + query => $query || undef, + } + ); + return XML::Atom::Entry->new(\($res->content)); +} + +sub post { + my ($self, $url, $entry, $header) = @_; + my $res = $self->request( + { + uri => $url, + content => $entry->as_xml, + header => $header || undef, + content_type => 'application/atom+xml', + } + ); + return (ref $entry)->new(\($res->content)); +} + +sub put { + my ($self, $args) = @_; + my $res = $self->request( + { + method => 'PUT', + uri => $args->{self}->editurl, + content => $args->{entry}->as_xml, + header => {'If-Match' => $args->{self}->etag }, + content_type => 'application/atom+xml', + } + ); + return XML::Atom::Entry->new(\($res->content)); +} + +1; +__END__ + +=head1 NAME + +Net::Google::Spreadsheets::UserAgent; + +=head1 AUTHOR + +Nobuo Danjou E<lt>[email protected]<gt> + +=cut diff --git a/t/02_spreadsheets.t b/t/02_spreadsheets.t index d537deb..50ed6aa 100644 --- a/t/02_spreadsheets.t +++ b/t/02_spreadsheets.t @@ -1,29 +1,33 @@ use strict; use Test::More; use Net::Google::Spreadsheets; my $service; BEGIN { plan skip_all => 'set TEST_NET_GOOGLE_SPREADSHEETS to run this test' unless $ENV{TEST_NET_GOOGLE_SPREADSHEETS}; eval "use Config::Pit"; plan skip_all => 'This Test needs Config::Pit.' if $@; my $config = pit_get('google.com', require => { 'username' => 'your username', 'password' => 'your password', } ); $service = Net::Google::Spreadsheets->new( username => $config->{username}, password => $config->{password}, ); my $title = 'test for Net::Google::Spreadsheets'; my $sheet = $service->spreadsheet({title => $title}); plan skip_all => "test spreadsheet '$title' doesn't exist." unless $sheet; - plan tests => 1; + plan tests => 5; } { my @sheets = $service->spreadsheets; ok scalar @sheets; + isa_ok $sheets[0], 'Net::Google::Spreadsheets::Spreadsheet'; + ok $sheets[0]->title; + ok $sheets[0]->key; + ok $sheets[0]->etag; }
lopnor/Net-Google-Spreadsheets
f5046b23d87edca16716fc42f3a999189d6be527
pass the tests
diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index d251908..7539bad 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,242 +1,239 @@ package Net::Google::Spreadsheets; use Moose; + +extends 'Net::Google::Spreadsheets::Base'; + use Carp; use Net::Google::AuthSub; use Net::Google::Spreadsheets::Spreadsheet; use LWP::UserAgent; use XML::Atom; use XML::Atom::Feed; use URI; use HTTP::Headers; our $VERSION = '0.01'; BEGIN { $XML::Atom::DefaultVersion = 1; } +has contents => ( + is => 'ro', + default => 'http://spreadsheets.google.com/feeds/spreadsheets/private/full' +); + has username => ( isa => 'Str', is => 'ro', required => 1 ); has password => ( isa => 'Str', is => 'ro', required => 1 ); has source => ( isa => 'Str', is => 'ro', required => 1, default => sub { __PACKAGE__.'-'.$VERSION }, ); has auth => ( isa => 'Str', is => 'rw', required => 1, lazy => 1, default => sub { my $self = shift; my $authsub = Net::Google::AuthSub->new( service => 'wise', source => $self->source, ); my $res = $authsub->login( $self->username, $self->password, ); $res->is_success or return; return $res->auth; }, ); -has host => ( - isa => 'Str', - is => 'ro', - required => 1, - default => 'spreadsheets.google.com', -); - has ua => ( isa => 'LWP::UserAgent', is => 'ro', required => 1, lazy => 1, default => sub { my $self = shift; my $ua = LWP::UserAgent->new( agent => $self->source, ); $ua->default_headers( HTTP::Headers->new( Authorization => sprintf('GoogleLogin auth=%s', $self->auth), GData_Version => 2, ) ); return $ua; } ); sub spreadsheets { - my ($self, $cond) = @_; - my $feed = $self->feed( - sprintf ('http://%s/feeds/spreadsheets/private/full', $self->host), - $cond - ); - return [ map { - Net::Google::Spreadsheets::Spreadsheet->new( - atom => $_, - service => $self, - ) - } $feed->entries ]; -} - -sub spreadsheet { my ($self, $args) = @_; - my $url = sprintf('http://%s/feeds/spreadsheets/', $self->host); my $cond = $args->{title} ? { title => $args->{title}, 'title-exact' => 'true' } : {}; my $feed = $self->feed( - $url."private/full", + $self->contents, $cond ); - my $entry; - for ( $feed->entries ) { - my ($key) = $_->id =~ m{^$url(.+)$}; - $entry = $_ and last if $args->{title} && $_->title eq $args->{title}; - $entry = $_ and last if $args->{key} && $key eq $args->{key}; - } - $entry or return; - return Net::Google::Spreadsheets::Spreadsheet->new( - atom => $entry, - service => $self, - ); + + return grep { + (!%$args && 1) + || + ($args->{key} && $_->key eq $args->{key}) + || + ($args->{title} && $_->title eq $args->{title}) + } map { + Net::Google::Spreadsheets::Spreadsheet->new( + atom => $_, + service => $self + ) + } $feed->entries; +} + +sub spreadsheet { + my ($self, $args) = @_; + return ($self->spreadsheets($args))[0]; } sub request { my ($self, $args) = @_; my $method = delete $args->{method}; $method ||= $args->{content} ? 'POST' : 'GET'; my $uri = URI->new($args->{'uri'}); $uri->query_form($args->{query}) if $args->{query}; my $req = HTTP::Request->new($method => "$uri"); $req->content($args->{content}) if $args->{content}; $req->header('Content-Type' => $args->{content_type}) if $args->{content_type}; if ($args->{header}) { while (my @pair = each %{$args->{header}}) { $req->header(@pair); } } my $res = $self->ua->request($req); unless ($res->is_success) { # warn $res->request->as_string; # warn $res->as_string; croak "request failed: ",$res->code; } return $res; } sub feed { my ($self, $url, $query) = @_; my $res = $self->request( { uri => $url, query => $query || undef, } ); return XML::Atom::Feed->new(\($res->content)); } sub entry { my ($self, $url, $query) = @_; my $res = $self->request( { uri => $url, query => $query || undef, } ); return XML::Atom::Entry->new(\($res->content)); } sub post { my ($self, $url, $entry, $header) = @_; my $res = $self->request( { uri => $url, content => $entry->as_xml, header => $header || undef, content_type => 'application/atom+xml', } ); return (ref $entry)->new(\($res->content)); # return XML::Atom::Entry->new(\($res->content)); } sub put { my ($self, $args) = @_; my $res = $self->request( { method => 'PUT', uri => $args->{self}->editurl, content => $args->{entry}->as_xml, header => {'If-Match' => $args->{self}->etag }, content_type => 'application/atom+xml', } ); return XML::Atom::Entry->new(\($res->content)); } 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); - my $spreadsheet = $api->spreadsheet({key => 'pZV-pns_sm9PtH2WowhU2Ew'}); + # find a spreadsheet by key + my $spreadsheet = $service->spreadsheet({key => 'pZV-pns_sm9PtH2WowhU2Ew'}); + + # find a spreadsheet by title + my $spreadsheet = $service->spreadsheet({title => 'list for new year cards'}); my $worksheet = $spreadsheet->worksheet(1); my @fields = $worksheet->fields(); my $inserted_row = $worksheet->insert( { name => 'danjou', } ); my @rows = $worksheet->rows; my $row = $worksheet->row(1); $row->update( { nick => 'lopnor', mail => '[email protected]', } ); =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Net/Google/Spreadsheets/Base.pm b/lib/Net/Google/Spreadsheets/Base.pm index b0e5591..20827d7 100644 --- a/lib/Net/Google/Spreadsheets/Base.pm +++ b/lib/Net/Google/Spreadsheets/Base.pm @@ -1,151 +1,159 @@ package Net::Google::Spreadsheets::Base; use Moose; use Carp; use Moose::Util::TypeConstraints; use Net::Google::Spreadsheets::Base; +use UNIVERSAL::require; has service => ( isa => 'Net::Google::Spreadsheets', is => 'ro', required => 1, lazy => 1, default => sub { shift->container->service }, ); my %ns = ( gd => 'http://schemas.google.com/g/2005', gs => 'http://schemas.google.com/spreadsheets/2006', gsx => 'http://schemas.google.com/spreadsheets/2006/extended', batch => 'http://schemas.google.com/gdata/batch', ); while (my ($prefix, $uri) = each %ns) { has $prefix.'ns' => ( isa => 'XML::Atom::Namespace', is => 'ro', required => 1, default => sub {XML::Atom::Namespace->new($prefix, $uri)}, ); } my %rel2label = ( edit => 'editurl', self => 'selfurl', ); for (values %rel2label) { has $_ => (isa => 'Str', is => 'ro'); } +has accessor => ( + isa => 'Str', + is => 'ro', +); + + + has atom => ( isa => 'XML::Atom::Entry', is => 'rw', trigger => sub { my ($self, $arg) = @_; my $id = $self->atom->get($self->ns, 'id'); croak "can't set different id!" if $self->id && $self->id ne $id; $self->_update_atom; }, handles => ['ns', 'elem', 'author'], ); has id => ( isa => 'Str', is => 'rw', ); has content => ( isa => 'Str', is => 'ro', ); has title => ( isa => 'Str', is => 'rw', default => 'untitled', trigger => sub {$_[0]->update} ); has etag => ( isa => 'Str', is => 'rw', ); has container => ( isa => 'Maybe[Net::Google::Spreadsheets::Base]', is => 'ro', ); sub _update_atom { my ($self) = @_; $self->{title} = $self->atom->title; $self->{id} = $self->atom->get($self->ns, 'id'); $self->etag($self->elem->getAttributeNS($self->gdns->{uri}, 'etag')); for ($self->atom->link) { my $label = $rel2label{$_->rel} or next; $self->{$label} = $_->href; } } sub list_contents { my ($self, $class, $cond) = @_; $self->content or return; my $feed = $self->service->feed($self->content, $cond); return map {$class->new(container => $self, atom => $_)} $feed->entries; } sub entry { my ($self) = @_; my $entry = XML::Atom::Entry->new; $entry->title($self->title) if $self->title; return $entry; } sub sync { my ($self) = @_; my $entry = $self->service->entry($self->selfurl); $self->atom($entry); } sub update { my ($self) = @_; $self->etag or return; my $atom = $self->service->put( { self => $self, entry => $self->entry, } ); $self->container->sync; $self->atom($atom); } sub delete { my $self = shift; my $res = $self->service->request( { uri => $self->editurl, method => 'DELETE', header => {'If-Match' => $self->etag}, } ); $self->container->sync if $res->is_success; return $res->is_success; } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Base - Base class of Net::Google::Spreadsheets::*. =head1 SYNOPSIS =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Spreadsheet.pm b/lib/Net/Google/Spreadsheets/Spreadsheet.pm index dd6bf92..c22d1e5 100644 --- a/lib/Net/Google/Spreadsheets/Spreadsheet.pm +++ b/lib/Net/Google/Spreadsheets/Spreadsheet.pm @@ -1,59 +1,68 @@ package Net::Google::Spreadsheets::Spreadsheet; use Moose; use XML::Atom; use Net::Google::Spreadsheets::Worksheet; use Path::Class; extends 'Net::Google::Spreadsheets::Base'; +has +accessor => ( + default => 'Net::Google::Spreadsheets::Worksheet' +); + has +title => ( is => 'ro', ); has key => ( isa => 'Str', is => 'ro', required => 1, lazy => 1, default => sub { my $self = shift; my $key = file(URI->new($self->id)->path)->basename; return $key; } ); after _update_atom => sub { my ($self) = @_; $self->{content} = $self->atom->content->elem->getAttribute('src'); }; +sub worksheet { + my ($self, $cond) = @_; + return ($self->worksheets($cond))[0]; +} + sub worksheets { my ($self, $cond) = @_; return $self->list_contents('Net::Google::Spreadsheets::Worksheet', $cond); } sub add_worksheet { my ($self, $args) = @_; my $entry = Net::Google::Spreadsheets::Worksheet->new($args)->entry; my $atom = $self->service->post($self->content, $entry); $self->sync; return Net::Google::Spreadsheets::Worksheet->new( container => $self, atom => $atom, ); } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Spreadsheet - Representation of spreadsheet =head1 SYNOPSIS =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Worksheet.pm b/lib/Net/Google/Spreadsheets/Worksheet.pm index 4b82941..69c29f9 100644 --- a/lib/Net/Google/Spreadsheets/Worksheet.pm +++ b/lib/Net/Google/Spreadsheets/Worksheet.pm @@ -1,111 +1,111 @@ package Net::Google::Spreadsheets::Worksheet; use Moose; use Net::Google::Spreadsheets::Row; use Net::Google::Spreadsheets::Cell; extends 'Net::Google::Spreadsheets::Base'; has row_count => ( isa => 'Int', is => 'rw', default => 100, trigger => sub {$_[0]->update} ); has col_count => ( isa => 'Int', is => 'rw', default => 20, trigger => sub {$_[0]->update} ); has cellsfeed => ( isa => 'Str', is => 'ro', ); around entry => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->gsns, 'rowCount', $self->row_count); $entry->set($self->gsns, 'colCount', $self->col_count); return $entry; }; after _update_atom => sub { my ($self) = @_; $self->{content} = $self->atom->content->elem->getAttribute('src'); ($self->{cellsfeed}) = map {$_->href} grep { $_->rel eq 'http://schemas.google.com/spreadsheets/2006#cellsfeed' } $self->atom->link; $self->{row_count} = $self->atom->get($self->gsns, 'rowCount'); $self->{col_count} = $self->atom->get($self->gsns, 'colCount'); }; sub rows { my ($self, $cond) = @_; return $self->list_contents('Net::Google::Spreadsheets::Row', $cond); } sub cell { my ($self, $row, $col) = @_; $self->cellsfeed or return; my $url = sprintf("%s/R%sC%s", $self->cellsfeed, $row, $col); return Net::Google::Spreadsheets::Cell->new( container => $self, atom => $self->service->entry($url), ); } sub batchupdate_cell { my ($self, @args) = @_; my $feed = XML::Atom::Feed->new; for ( @args ) { my $id = sprintf("%s/R%sC%s",$self->cellsfeed, $_->{row}, $_->{col}); $_->{id} = $_->{editurl} = $id; my $entry = Net::Google::Spreadsheets::Cell->new($_)->entry; $entry->set($self->batchns, operation => '', {type => 'update'}); $entry->set($self->batchns, id => $id); $feed->add_entry($entry); } my $res_feed = $self->service->post($self->cellsfeed."/batch", $feed, {'If-Match' => '*'}); $self->sync; return map { Net::Google::Spreadsheets::Cell->new( atom => $_, container => $self, ) } grep { my ($node) = $_->elem->getElementsByTagNameNS($self->batchns->{uri}, 'status'); $node->getAttribute('code') == 200; } $res_feed->entries; } -sub insert_row { +sub add_row { my ($self, $args) = @_; my $entry = Net::Google::Spreadsheets::Row->new( content => $args, )->entry; my $atom = $self->service->post($self->content, $entry); $self->sync; return Net::Google::Spreadsheets::Row->new( container => $self, atom => $atom, ); } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Worksheet - Representation of worksheet. =head1 SYNOPSIS =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/t/02_spreadsheets.t b/t/02_spreadsheets.t index 89a3f10..d537deb 100644 --- a/t/02_spreadsheets.t +++ b/t/02_spreadsheets.t @@ -1,29 +1,29 @@ use strict; use Test::More; use Net::Google::Spreadsheets; my $service; BEGIN { plan skip_all => 'set TEST_NET_GOOGLE_SPREADSHEETS to run this test' unless $ENV{TEST_NET_GOOGLE_SPREADSHEETS}; eval "use Config::Pit"; plan skip_all => 'This Test needs Config::Pit.' if $@; my $config = pit_get('google.com', require => { 'username' => 'your username', 'password' => 'your password', } ); $service = Net::Google::Spreadsheets->new( username => $config->{username}, password => $config->{password}, ); my $title = 'test for Net::Google::Spreadsheets'; my $sheet = $service->spreadsheet({title => $title}); plan skip_all => "test spreadsheet '$title' doesn't exist." unless $sheet; plan tests => 1; } -SKIP: { - my $sheets = $service->spreadsheets; - ok scalar @$sheets; +{ + my @sheets = $service->spreadsheets; + ok scalar @sheets; } diff --git a/t/03_spreadsheet.t b/t/03_spreadsheet.t index 40d7c1b..f3c19d8 100644 --- a/t/03_spreadsheet.t +++ b/t/03_spreadsheet.t @@ -1,43 +1,58 @@ use strict; use Test::More; use Net::Google::Spreadsheets; my ($service, $config); BEGIN { plan skip_all => 'set TEST_NET_GOOGLE_SPREADSHEETS to run this test' unless $ENV{TEST_NET_GOOGLE_SPREADSHEETS}; eval "use Config::Pit"; plan skip_all => 'This Test needs Config::Pit.' if $@; $config = pit_get('google.com', require => { 'username' => 'your username', 'password' => 'your password', } ); $service = Net::Google::Spreadsheets->new( username => $config->{username}, password => $config->{password}, ); my $title = 'test for Net::Google::Spreadsheets'; my $sheet = $service->spreadsheet({title => $title}); plan skip_all => "test spreadsheet '$title' doesn't exist." unless $sheet; - plan tests => 10; + plan tests => 15; +} +{ + my $title = 'non exisitng spreadsheet name'; + my $ss = $service->spreadsheet({title => $title}); + is $ss, undef; + my @sss = $service->spreadsheets({title => $title}); + is scalar @sss, 0; +} +{ + my $key = 'foobar'; + my $ss = $service->spreadsheet({key => $key}); + is $ss, undef; + my @sss = $service->spreadsheets({key => $key}); + is scalar @sss, 0; } { my $title = 'test for Net::Google::Spreadsheets'; my $ss = $service->spreadsheet({title => $title}); ok $ss; isa_ok $ss, 'Net::Google::Spreadsheets::Spreadsheet'; is $ss->title, $title; like $ss->id, qr{^http://spreadsheets.google.com/feeds/spreadsheets/}; isa_ok $ss->author, 'XML::Atom::Person'; is $ss->author->email, $config->{username}; my $key = $ss->key; ok length $key, 'key defined'; { my $ss2 = $service->spreadsheet({key => $key}); ok $ss2; isa_ok $ss2, 'Net::Google::Spreadsheets::Spreadsheet'; is $ss2->key, $key; + is $ss2->title, $title; } } diff --git a/t/04_worksheet.t b/t/04_worksheet.t index 0331443..9f40ed8 100644 --- a/t/04_worksheet.t +++ b/t/04_worksheet.t @@ -1,63 +1,76 @@ use strict; use Test::More; use Net::Google::Spreadsheets; my $ss; BEGIN { plan skip_all => 'set TEST_NET_GOOGLE_SPREADSHEETS to run this test' unless $ENV{TEST_NET_GOOGLE_SPREADSHEETS}; eval "use Config::Pit"; plan skip_all => 'This Test needs Config::Pit.' if $@; my $config = pit_get('google.com', require => { 'username' => 'your username', 'password' => 'your password', } ); my $service = Net::Google::Spreadsheets->new( username => $config->{username}, password => $config->{password}, ); my $title = 'test for Net::Google::Spreadsheets'; $ss = $service->spreadsheet({title => $title}); plan skip_all => "test spreadsheet '$title' doesn't exist." unless $ss; - plan tests => 28; + plan tests => 27; +} +{ + my @worksheets = $ss->worksheets; + ok scalar @worksheets; +} +{ + my $title = 'new worksheet'; + my $ws = $ss->add_worksheet({title => $title}); + isa_ok $ws, 'Net::Google::Spreadsheets::Worksheet'; + is $ws->title, $title; + my $ws2 = $ss->worksheet({title => $title}); + isa_ok $ws2, 'Net::Google::Spreadsheets::Worksheet'; + is $ws2->title, $title; } { my ($ws) = $ss->worksheets; isa_ok $ws, 'Net::Google::Spreadsheets::Worksheet'; } { my $before = scalar $ss->worksheets; my $ws = $ss->add_worksheet; isa_ok $ws, 'Net::Google::Spreadsheets::Worksheet'; is scalar $ss->worksheets, $before + 1; ok grep {$_->id eq $ws->id} $ss->worksheets; } { my $ws = ($ss->worksheets)[-1]; my $title = $ws->title . '+add'; is $ws->title($title), $title; is $ws->atom->title, $title; is $ws->title, $title; } { my $ws = ($ss->worksheets)[-1]; - for (1 .. 3) { + for (1 .. 2) { my $col_count = $ws->col_count + 1; my $row_count = $ws->row_count + 1; is $ws->col_count($col_count), $col_count; is $ws->atom->get($ws->gsns, 'colCount'), $col_count; is $ws->col_count, $col_count; is $ws->row_count($row_count), $row_count; is $ws->atom->get($ws->gsns, 'rowCount'), $row_count; is $ws->row_count, $row_count; } } { my $before = scalar $ss->worksheets; my $ws = ($ss->worksheets)[-1]; ok $ws->delete; is scalar $ss->worksheets, $before - 1; ok ! grep {$_ == $ws} $ss->worksheets; } diff --git a/t/06_rows.t b/t/06_rows.t index 200e8e9..ab4fcc4 100644 --- a/t/06_rows.t +++ b/t/06_rows.t @@ -1,55 +1,55 @@ use strict; use Test::More; use Net::Google::Spreadsheets; my $ws; BEGIN { plan skip_all => 'set TEST_NET_GOOGLE_SPREADSHEETS to run this test' unless $ENV{TEST_NET_GOOGLE_SPREADSHEETS}; eval "use Config::Pit"; plan skip_all => 'This Test needs Config::Pit.' if $@; my $config = pit_get('google.com', require => { 'username' => 'your username', 'password' => 'your password', } ); my $service = Net::Google::Spreadsheets->new( username => $config->{username}, password => $config->{password}, ); my $title = 'test for Net::Google::Spreadsheets'; my $ss = $service->spreadsheet({title => $title}); plan skip_all => "test spreadsheet '$title' doesn't exist." unless $ss; plan tests => 8; $ws = $ss->add_worksheet; } { is scalar $ws->rows, 0; $ws->batchupdate_cell( {col => 1, row => 1, input_value => 'name'}, {col => 2, row => 1, input_value => 'mail'}, {col => 3, row => 1, input_value => 'nick'}, ); is scalar $ws->rows, 0; my $value = { name => 'Nobuo Danjou', mail => '[email protected]', nick => 'lopnor', }; - my $row = $ws->insert_row($value); + my $row = $ws->add_row($value); isa_ok $row, 'Net::Google::Spreadsheets::Row'; is_deeply $row->content, $value; my $value2 = { name => 'Kazuhiro Osawa', nick => 'yappo', }; $row->content($value2); is_deeply $row->content, $value2; is scalar $ws->rows, 1; ok $row->delete; is scalar $ws->rows, 0; } END { $ws->delete; }
lopnor/Net-Google-Spreadsheets
5d73096dfeb2d2e867f9fe31aabdbd9c7c278135
some fix (forgot ditails)
diff --git a/MANIFEST b/MANIFEST index f03fd12..37ef342 100644 --- a/MANIFEST +++ b/MANIFEST @@ -1,40 +1,39 @@ Changes inc/Module/Install.pm inc/Module/Install/AuthorTests.pm inc/Module/Install/Base.pm inc/Module/Install/Can.pm inc/Module/Install/Fetch.pm inc/Module/Install/Include.pm inc/Module/Install/Makefile.pm inc/Module/Install/Metadata.pm inc/Module/Install/TestBase.pm inc/Module/Install/Win32.pm inc/Module/Install/WriteAll.pm inc/Spiffy.pm inc/Test/Base.pm inc/Test/Base/Filter.pm inc/Test/Builder.pm inc/Test/Builder/Module.pm inc/Test/More.pm lib/Net/Google/Spreadsheets.pm lib/Net/Google/Spreadsheets/Base.pm lib/Net/Google/Spreadsheets/Cell.pm lib/Net/Google/Spreadsheets/Row.pm lib/Net/Google/Spreadsheets/Spreadsheet.pm lib/Net/Google/Spreadsheets/Worksheet.pm Makefile.PL MANIFEST This list of files META.yml README t/00_compile.t t/01_instanciate.t t/02_spreadsheets.t t/03_spreadsheet.t t/04_worksheet.t t/05_cell.t -t/05_rows.t t/06_rows.t xt/01_podspell.t xt/02_perlcritic.t xt/03_pod.t xt/perlcriticrc diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index 187a940..d251908 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,244 +1,242 @@ package Net::Google::Spreadsheets; use Moose; use Carp; use Net::Google::AuthSub; use Net::Google::Spreadsheets::Spreadsheet; use LWP::UserAgent; use XML::Atom; use XML::Atom::Feed; use URI; use HTTP::Headers; our $VERSION = '0.01'; BEGIN { $XML::Atom::DefaultVersion = 1; } has username => ( isa => 'Str', is => 'ro', required => 1 ); has password => ( isa => 'Str', is => 'ro', required => 1 ); has source => ( isa => 'Str', is => 'ro', required => 1, default => sub { __PACKAGE__.'-'.$VERSION }, ); has auth => ( isa => 'Str', is => 'rw', required => 1, lazy => 1, default => sub { my $self = shift; my $authsub = Net::Google::AuthSub->new( service => 'wise', source => $self->source, ); my $res = $authsub->login( $self->username, $self->password, ); $res->is_success or return; return $res->auth; }, ); has host => ( isa => 'Str', is => 'ro', required => 1, default => 'spreadsheets.google.com', ); has ua => ( isa => 'LWP::UserAgent', is => 'ro', required => 1, lazy => 1, default => sub { my $self = shift; my $ua = LWP::UserAgent->new( agent => $self->source, ); $ua->default_headers( HTTP::Headers->new( Authorization => sprintf('GoogleLogin auth=%s', $self->auth), GData_Version => 2, ) ); return $ua; } ); sub spreadsheets { my ($self, $cond) = @_; my $feed = $self->feed( sprintf ('http://%s/feeds/spreadsheets/private/full', $self->host), $cond ); return [ map { Net::Google::Spreadsheets::Spreadsheet->new( atom => $_, service => $self, ) } $feed->entries ]; } sub spreadsheet { my ($self, $args) = @_; my $url = sprintf('http://%s/feeds/spreadsheets/', $self->host); my $cond = $args->{title} ? { title => $args->{title}, 'title-exact' => 'true' } : {}; my $feed = $self->feed( $url."private/full", $cond ); my $entry; for ( $feed->entries ) { my ($key) = $_->id =~ m{^$url(.+)$}; $entry = $_ and last if $args->{title} && $_->title eq $args->{title}; $entry = $_ and last if $args->{key} && $key eq $args->{key}; } $entry or return; return Net::Google::Spreadsheets::Spreadsheet->new( atom => $entry, service => $self, ); } sub request { my ($self, $args) = @_; my $method = delete $args->{method}; $method ||= $args->{content} ? 'POST' : 'GET'; my $uri = URI->new($args->{'uri'}); $uri->query_form($args->{query}) if $args->{query}; my $req = HTTP::Request->new($method => "$uri"); $req->content($args->{content}) if $args->{content}; $req->header('Content-Type' => $args->{content_type}) if $args->{content_type}; if ($args->{header}) { while (my @pair = each %{$args->{header}}) { $req->header(@pair); } } my $res = $self->ua->request($req); + unless ($res->is_success) { # warn $res->request->as_string; # warn $res->as_string; - unless ($res->is_success) { - warn $res->request->as_string; - warn $res->as_string; croak "request failed: ",$res->code; } return $res; } sub feed { my ($self, $url, $query) = @_; my $res = $self->request( { uri => $url, query => $query || undef, } ); return XML::Atom::Feed->new(\($res->content)); } sub entry { my ($self, $url, $query) = @_; my $res = $self->request( { uri => $url, query => $query || undef, } ); return XML::Atom::Entry->new(\($res->content)); } sub post { my ($self, $url, $entry, $header) = @_; my $res = $self->request( { uri => $url, content => $entry->as_xml, header => $header || undef, content_type => 'application/atom+xml', } ); return (ref $entry)->new(\($res->content)); # return XML::Atom::Entry->new(\($res->content)); } sub put { my ($self, $args) = @_; my $res = $self->request( { method => 'PUT', uri => $args->{self}->editurl, content => $args->{entry}->as_xml, header => {'If-Match' => $args->{self}->etag }, content_type => 'application/atom+xml', } ); return XML::Atom::Entry->new(\($res->content)); } 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; my $service = Net::Google::Spreadsheets->new( username => '[email protected]', password => 'mypassword' ); my @spreadsheets = $service->spreadsheets(); my $spreadsheet = $api->spreadsheet({key => 'pZV-pns_sm9PtH2WowhU2Ew'}); my $worksheet = $spreadsheet->worksheet(1); my @fields = $worksheet->fields(); my $inserted_row = $worksheet->insert( { name => 'danjou', } ); my @rows = $worksheet->rows; my $row = $worksheet->row(1); $row->update( { nick => 'lopnor', mail => '[email protected]', } ); =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Net/Google/Spreadsheets/Base.pm b/lib/Net/Google/Spreadsheets/Base.pm index 3e317d5..b0e5591 100644 --- a/lib/Net/Google/Spreadsheets/Base.pm +++ b/lib/Net/Google/Spreadsheets/Base.pm @@ -1,156 +1,151 @@ package Net::Google::Spreadsheets::Base; use Moose; use Carp; use Moose::Util::TypeConstraints; use Net::Google::Spreadsheets::Base; has service => ( isa => 'Net::Google::Spreadsheets', is => 'ro', required => 1, lazy => 1, default => sub { shift->container->service }, ); my %ns = ( gd => 'http://schemas.google.com/g/2005', gs => 'http://schemas.google.com/spreadsheets/2006', gsx => 'http://schemas.google.com/spreadsheets/2006/extended', batch => 'http://schemas.google.com/gdata/batch', ); while (my ($prefix, $uri) = each %ns) { - has $prefix => ( + has $prefix.'ns' => ( isa => 'XML::Atom::Namespace', is => 'ro', required => 1, default => sub {XML::Atom::Namespace->new($prefix, $uri)}, ); } my %rel2label = ( edit => 'editurl', self => 'selfurl', ); for (values %rel2label) { has $_ => (isa => 'Str', is => 'ro'); } has atom => ( isa => 'XML::Atom::Entry', is => 'rw', trigger => sub { my ($self, $arg) = @_; - my $id = $self->atom->get($self->atom->ns, 'id'); + my $id = $self->atom->get($self->ns, 'id'); croak "can't set different id!" if $self->id && $self->id ne $id; $self->_update_atom; }, + handles => ['ns', 'elem', 'author'], ); has id => ( isa => 'Str', is => 'rw', ); has content => ( isa => 'Str', is => 'ro', ); has title => ( isa => 'Str', is => 'rw', default => 'untitled', trigger => sub {$_[0]->update} ); -has author => ( - isa => 'XML::Atom::Person', - is => 'rw', -); - has etag => ( isa => 'Str', is => 'rw', ); has container => ( isa => 'Maybe[Net::Google::Spreadsheets::Base]', is => 'ro', ); sub _update_atom { my ($self) = @_; $self->{title} = $self->atom->title; - $self->{id} = $self->atom->get($self->atom->ns, 'id'); - $self->{author} = $self->atom->author; - $self->etag($self->atom->elem->getAttributeNS($self->gd->{uri}, 'etag')); + $self->{id} = $self->atom->get($self->ns, 'id'); + $self->etag($self->elem->getAttributeNS($self->gdns->{uri}, 'etag')); for ($self->atom->link) { my $label = $rel2label{$_->rel} or next; $self->{$label} = $_->href; } } sub list_contents { my ($self, $class, $cond) = @_; $self->content or return; my $feed = $self->service->feed($self->content, $cond); return map {$class->new(container => $self, atom => $_)} $feed->entries; } sub entry { my ($self) = @_; my $entry = XML::Atom::Entry->new; $entry->title($self->title) if $self->title; return $entry; } sub sync { my ($self) = @_; my $entry = $self->service->entry($self->selfurl); $self->atom($entry); } sub update { my ($self) = @_; $self->etag or return; my $atom = $self->service->put( { self => $self, entry => $self->entry, } ); $self->container->sync; $self->atom($atom); } sub delete { my $self = shift; my $res = $self->service->request( { uri => $self->editurl, method => 'DELETE', header => {'If-Match' => $self->etag}, } ); $self->container->sync if $res->is_success; return $res->is_success; } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Base - Base class of Net::Google::Spreadsheets::*. =head1 SYNOPSIS =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Cell.pm b/lib/Net/Google/Spreadsheets/Cell.pm index 44e7219..acd5e4a 100644 --- a/lib/Net/Google/Spreadsheets/Cell.pm +++ b/lib/Net/Google/Spreadsheets/Cell.pm @@ -1,64 +1,64 @@ package Net::Google::Spreadsheets::Cell; use Moose; extends 'Net::Google::Spreadsheets::Base'; has row => ( isa => 'Int', is => 'ro', ); has col => ( isa => 'Int', is => 'ro', ); has input_value => ( isa => 'Str', is => 'rw', trigger => sub {$_[0]->update}, ); after _update_atom => sub { my ($self) = @_; - my ($elem) = $self->atom->elem->getElementsByTagNameNS($self->gs->{uri}, 'cell'); + my ($elem) = $self->elem->getElementsByTagNameNS($self->gsns->{uri}, 'cell'); $self->{row} = $elem->getAttribute('row'); $self->{col} = $elem->getAttribute('col'); $self->{input_value} = $elem->getAttribute('inputValue'); $self->{content} = $elem->textContent || ''; }; around entry => sub { my ($next, $self) = @_; my $entry = $next->($self); - $entry->set($self->gs, 'cell', '', + $entry->set($self->gsns, 'cell', '', { row => $self->row, col => $self->col, inputValue => $self->input_value, } ); my $link = XML::Atom::Link->new; $link->rel('edit'); $link->type('application/atom+xml'); $link->href($self->editurl); $entry->link($link); $entry->id($self->id); return $entry; }; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Cell - A representation class for Google Spreadsheet cell. =head1 SYNOPSIS =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Row.pm b/lib/Net/Google/Spreadsheets/Row.pm index 138b2c7..a3d0ab6 100644 --- a/lib/Net/Google/Spreadsheets/Row.pm +++ b/lib/Net/Google/Spreadsheets/Row.pm @@ -1,43 +1,43 @@ package Net::Google::Spreadsheets::Row; use Moose; extends 'Net::Google::Spreadsheets::Base'; has +content => ( isa => 'HashRef', is => 'rw', default => sub { +{} }, trigger => sub {$_[0]->update}, ); after _update_atom => sub { my ($self) = @_; - for my $node ($self->atom->elem->getElementsByTagNameNS($self->gsx->{uri}, '*')) { + for my $node ($self->elem->getElementsByTagNameNS($self->gsxns->{uri}, '*')) { $self->{content}->{$node->localname} = $node->textContent; } }; around entry => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->{content}}) { - $entry->set($self->gsx, $key, $value); + $entry->set($self->gsxns, $key, $value); } return $entry; }; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Row - A representation class for Google Spreadsheet row. =head1 SYNOPSIS =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Worksheet.pm b/lib/Net/Google/Spreadsheets/Worksheet.pm index 0bb5c89..4b82941 100644 --- a/lib/Net/Google/Spreadsheets/Worksheet.pm +++ b/lib/Net/Google/Spreadsheets/Worksheet.pm @@ -1,111 +1,111 @@ package Net::Google::Spreadsheets::Worksheet; use Moose; use Net::Google::Spreadsheets::Row; use Net::Google::Spreadsheets::Cell; extends 'Net::Google::Spreadsheets::Base'; has row_count => ( isa => 'Int', is => 'rw', default => 100, trigger => sub {$_[0]->update} ); has col_count => ( isa => 'Int', is => 'rw', default => 20, trigger => sub {$_[0]->update} ); has cellsfeed => ( isa => 'Str', is => 'ro', ); around entry => sub { my ($next, $self) = @_; my $entry = $next->($self); - $entry->set($self->gs, 'rowCount', $self->row_count); - $entry->set($self->gs, 'colCount', $self->col_count); + $entry->set($self->gsns, 'rowCount', $self->row_count); + $entry->set($self->gsns, 'colCount', $self->col_count); return $entry; }; after _update_atom => sub { my ($self) = @_; $self->{content} = $self->atom->content->elem->getAttribute('src'); ($self->{cellsfeed}) = map {$_->href} grep { $_->rel eq 'http://schemas.google.com/spreadsheets/2006#cellsfeed' } $self->atom->link; - $self->{row_count} = $self->atom->get($self->gs, 'rowCount'); - $self->{col_count} = $self->atom->get($self->gs, 'colCount'); + $self->{row_count} = $self->atom->get($self->gsns, 'rowCount'); + $self->{col_count} = $self->atom->get($self->gsns, 'colCount'); }; sub rows { my ($self, $cond) = @_; return $self->list_contents('Net::Google::Spreadsheets::Row', $cond); } sub cell { my ($self, $row, $col) = @_; $self->cellsfeed or return; - my $url = sprintf "%s/R%sC%s", $self->cellsfeed, $row, $col; + my $url = sprintf("%s/R%sC%s", $self->cellsfeed, $row, $col); return Net::Google::Spreadsheets::Cell->new( container => $self, atom => $self->service->entry($url), ); } sub batchupdate_cell { my ($self, @args) = @_; my $feed = XML::Atom::Feed->new; for ( @args ) { my $id = sprintf("%s/R%sC%s",$self->cellsfeed, $_->{row}, $_->{col}); $_->{id} = $_->{editurl} = $id; my $entry = Net::Google::Spreadsheets::Cell->new($_)->entry; - $entry->set($self->batch, operation => '', {type => 'update'}); - $entry->set($self->batch, id => $id); + $entry->set($self->batchns, operation => '', {type => 'update'}); + $entry->set($self->batchns, id => $id); $feed->add_entry($entry); } my $res_feed = $self->service->post($self->cellsfeed."/batch", $feed, {'If-Match' => '*'}); $self->sync; return map { Net::Google::Spreadsheets::Cell->new( atom => $_, container => $self, ) } grep { - my ($node) = $_->elem->getElementsByTagNameNS($self->batch->{uri}, 'status'); + my ($node) = $_->elem->getElementsByTagNameNS($self->batchns->{uri}, 'status'); $node->getAttribute('code') == 200; } $res_feed->entries; } sub insert_row { my ($self, $args) = @_; my $entry = Net::Google::Spreadsheets::Row->new( content => $args, )->entry; my $atom = $self->service->post($self->content, $entry); $self->sync; return Net::Google::Spreadsheets::Row->new( container => $self, atom => $atom, ); } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Worksheet - Representation of worksheet. =head1 SYNOPSIS =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/t/04_worksheet.t b/t/04_worksheet.t index 3c24d61..0331443 100644 --- a/t/04_worksheet.t +++ b/t/04_worksheet.t @@ -1,71 +1,63 @@ use strict; use Test::More; use Net::Google::Spreadsheets; my $ss; BEGIN { plan skip_all => 'set TEST_NET_GOOGLE_SPREADSHEETS to run this test' unless $ENV{TEST_NET_GOOGLE_SPREADSHEETS}; eval "use Config::Pit"; plan skip_all => 'This Test needs Config::Pit.' if $@; my $config = pit_get('google.com', require => { 'username' => 'your username', 'password' => 'your password', } ); my $service = Net::Google::Spreadsheets->new( username => $config->{username}, password => $config->{password}, ); my $title = 'test for Net::Google::Spreadsheets'; $ss = $service->spreadsheet({title => $title}); plan skip_all => "test spreadsheet '$title' doesn't exist." unless $ss; - plan tests => 18; + plan tests => 28; } { my ($ws) = $ss->worksheets; isa_ok $ws, 'Net::Google::Spreadsheets::Worksheet'; } { my $before = scalar $ss->worksheets; my $ws = $ss->add_worksheet; isa_ok $ws, 'Net::Google::Spreadsheets::Worksheet'; is scalar $ss->worksheets, $before + 1; ok grep {$_->id eq $ws->id} $ss->worksheets; } { my $ws = ($ss->worksheets)[-1]; my $title = $ws->title . '+add'; is $ws->title($title), $title; is $ws->atom->title, $title; is $ws->title, $title; } { my $ws = ($ss->worksheets)[-1]; - my $etag_before = $ws->etag; - my $before = $ws->col_count; - my $col_count = $before + 1; - is $ws->col_count($col_count), $col_count; - is $ws->atom->get($ws->gs, 'colCount'), $col_count; - is $ws->col_count, $col_count; - isnt $ws->etag, $etag_before; -} -{ - my $ws = ($ss->worksheets)[-1]; - my $ss_etag_before = $ss->etag; - my $etag_before = $ws->etag; - my $before = $ws->row_count; - my $row_count = $before + 1; - is $ws->row_count($row_count), $row_count; - is $ws->atom->get($ws->gs, 'rowCount'), $row_count; - is $ws->row_count, $row_count; - isnt $ws->etag, $etag_before; + for (1 .. 3) { + my $col_count = $ws->col_count + 1; + my $row_count = $ws->row_count + 1; + is $ws->col_count($col_count), $col_count; + is $ws->atom->get($ws->gsns, 'colCount'), $col_count; + is $ws->col_count, $col_count; + is $ws->row_count($row_count), $row_count; + is $ws->atom->get($ws->gsns, 'rowCount'), $row_count; + is $ws->row_count, $row_count; + } } { my $before = scalar $ss->worksheets; my $ws = ($ss->worksheets)[-1]; ok $ws->delete; is scalar $ss->worksheets, $before - 1; ok ! grep {$_ == $ws} $ss->worksheets; }
lopnor/Net-Google-Spreadsheets
656746840779dd935adb4814e36dfdf3d6dc1a44
tiny fix
diff --git a/lib/Net/Google/Spreadsheets/Spreadsheet.pm b/lib/Net/Google/Spreadsheets/Spreadsheet.pm index 92be2d3..dd6bf92 100644 --- a/lib/Net/Google/Spreadsheets/Spreadsheet.pm +++ b/lib/Net/Google/Spreadsheets/Spreadsheet.pm @@ -1,59 +1,59 @@ package Net::Google::Spreadsheets::Spreadsheet; use Moose; use XML::Atom; use Net::Google::Spreadsheets::Worksheet; use Path::Class; extends 'Net::Google::Spreadsheets::Base'; has +title => ( is => 'ro', ); has key => ( isa => 'Str', is => 'ro', required => 1, lazy => 1, default => sub { my $self = shift; my $key = file(URI->new($self->id)->path)->basename; return $key; } ); after _update_atom => sub { my ($self) = @_; $self->{content} = $self->atom->content->elem->getAttribute('src'); }; sub worksheets { my ($self, $cond) = @_; return $self->list_contents('Net::Google::Spreadsheets::Worksheet', $cond); } sub add_worksheet { my ($self, $args) = @_; - my $entry = Net::Google::Spreadsheets::Worksheet->new->entry; + my $entry = Net::Google::Spreadsheets::Worksheet->new($args)->entry; my $atom = $self->service->post($self->content, $entry); $self->sync; return Net::Google::Spreadsheets::Worksheet->new( container => $self, atom => $atom, ); } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Spreadsheet - Representation of spreadsheet =head1 SYNOPSIS =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Worksheet.pm b/lib/Net/Google/Spreadsheets/Worksheet.pm index 0132075..0bb5c89 100644 --- a/lib/Net/Google/Spreadsheets/Worksheet.pm +++ b/lib/Net/Google/Spreadsheets/Worksheet.pm @@ -1,112 +1,111 @@ package Net::Google::Spreadsheets::Worksheet; use Moose; use Net::Google::Spreadsheets::Row; use Net::Google::Spreadsheets::Cell; extends 'Net::Google::Spreadsheets::Base'; has row_count => ( isa => 'Int', is => 'rw', default => 100, trigger => sub {$_[0]->update} ); has col_count => ( isa => 'Int', is => 'rw', default => 20, trigger => sub {$_[0]->update} ); has cellsfeed => ( isa => 'Str', is => 'ro', ); around entry => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->gs, 'rowCount', $self->row_count); $entry->set($self->gs, 'colCount', $self->col_count); return $entry; }; after _update_atom => sub { my ($self) = @_; $self->{content} = $self->atom->content->elem->getAttribute('src'); ($self->{cellsfeed}) = map {$_->href} grep { $_->rel eq 'http://schemas.google.com/spreadsheets/2006#cellsfeed' } $self->atom->link; $self->{row_count} = $self->atom->get($self->gs, 'rowCount'); $self->{col_count} = $self->atom->get($self->gs, 'colCount'); }; sub rows { my ($self, $cond) = @_; return $self->list_contents('Net::Google::Spreadsheets::Row', $cond); } sub cell { my ($self, $row, $col) = @_; $self->cellsfeed or return; my $url = sprintf "%s/R%sC%s", $self->cellsfeed, $row, $col; return Net::Google::Spreadsheets::Cell->new( container => $self, atom => $self->service->entry($url), ); } sub batchupdate_cell { my ($self, @args) = @_; my $feed = XML::Atom::Feed->new; for ( @args ) { my $id = sprintf("%s/R%sC%s",$self->cellsfeed, $_->{row}, $_->{col}); - $_->{id} = $id; - $_->{editurl} = $id; + $_->{id} = $_->{editurl} = $id; my $entry = Net::Google::Spreadsheets::Cell->new($_)->entry; $entry->set($self->batch, operation => '', {type => 'update'}); $entry->set($self->batch, id => $id); $feed->add_entry($entry); } my $res_feed = $self->service->post($self->cellsfeed."/batch", $feed, {'If-Match' => '*'}); $self->sync; return map { Net::Google::Spreadsheets::Cell->new( atom => $_, container => $self, ) } grep { my ($node) = $_->elem->getElementsByTagNameNS($self->batch->{uri}, 'status'); $node->getAttribute('code') == 200; } $res_feed->entries; } sub insert_row { my ($self, $args) = @_; my $entry = Net::Google::Spreadsheets::Row->new( content => $args, )->entry; my $atom = $self->service->post($self->content, $entry); $self->sync; return Net::Google::Spreadsheets::Row->new( container => $self, atom => $atom, ); } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Worksheet - Representation of worksheet. =head1 SYNOPSIS =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut
lopnor/Net-Google-Spreadsheets
252d0d9fb94157987660dcdfb82abd7105550951
fix typo in the pod
diff --git a/lib/Net/Google/Spreadsheets/Base.pm b/lib/Net/Google/Spreadsheets/Base.pm index df77a39..3e317d5 100644 --- a/lib/Net/Google/Spreadsheets/Base.pm +++ b/lib/Net/Google/Spreadsheets/Base.pm @@ -1,149 +1,156 @@ package Net::Google::Spreadsheets::Base; use Moose; use Carp; use Moose::Util::TypeConstraints; use Net::Google::Spreadsheets::Base; has service => ( isa => 'Net::Google::Spreadsheets', is => 'ro', required => 1, lazy => 1, default => sub { shift->container->service }, ); my %ns = ( gd => 'http://schemas.google.com/g/2005', gs => 'http://schemas.google.com/spreadsheets/2006', gsx => 'http://schemas.google.com/spreadsheets/2006/extended', batch => 'http://schemas.google.com/gdata/batch', ); while (my ($prefix, $uri) = each %ns) { has $prefix => ( isa => 'XML::Atom::Namespace', is => 'ro', required => 1, default => sub {XML::Atom::Namespace->new($prefix, $uri)}, ); } my %rel2label = ( edit => 'editurl', self => 'selfurl', ); for (values %rel2label) { has $_ => (isa => 'Str', is => 'ro'); } has atom => ( isa => 'XML::Atom::Entry', is => 'rw', trigger => sub { my ($self, $arg) = @_; my $id = $self->atom->get($self->atom->ns, 'id'); croak "can't set different id!" if $self->id && $self->id ne $id; $self->_update_atom; }, ); has id => ( isa => 'Str', is => 'rw', ); has content => ( isa => 'Str', is => 'ro', ); has title => ( isa => 'Str', is => 'rw', default => 'untitled', trigger => sub {$_[0]->update} ); has author => ( isa => 'XML::Atom::Person', is => 'rw', ); has etag => ( isa => 'Str', is => 'rw', ); has container => ( isa => 'Maybe[Net::Google::Spreadsheets::Base]', is => 'ro', ); sub _update_atom { my ($self) = @_; $self->{title} = $self->atom->title; $self->{id} = $self->atom->get($self->atom->ns, 'id'); $self->{author} = $self->atom->author; $self->etag($self->atom->elem->getAttributeNS($self->gd->{uri}, 'etag')); for ($self->atom->link) { my $label = $rel2label{$_->rel} or next; $self->{$label} = $_->href; } } sub list_contents { my ($self, $class, $cond) = @_; $self->content or return; my $feed = $self->service->feed($self->content, $cond); return map {$class->new(container => $self, atom => $_)} $feed->entries; } sub entry { my ($self) = @_; my $entry = XML::Atom::Entry->new; $entry->title($self->title) if $self->title; return $entry; } sub sync { my ($self) = @_; my $entry = $self->service->entry($self->selfurl); $self->atom($entry); } sub update { my ($self) = @_; $self->etag or return; my $atom = $self->service->put( { self => $self, entry => $self->entry, } ); $self->container->sync; $self->atom($atom); } sub delete { my $self = shift; my $res = $self->service->request( { uri => $self->editurl, method => 'DELETE', header => {'If-Match' => $self->etag}, } ); $self->container->sync if $res->is_success; return $res->is_success; } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Base - Base class of Net::Google::Spreadsheets::*. +=head1 SYNOPSIS + +=head1 AUTHOR + +Nobuo Danjou E<lt>[email protected]<gt> + =cut + diff --git a/lib/Net/Google/Spreadsheets/Cell.pm b/lib/Net/Google/Spreadsheets/Cell.pm index 8f0b395..44e7219 100644 --- a/lib/Net/Google/Spreadsheets/Cell.pm +++ b/lib/Net/Google/Spreadsheets/Cell.pm @@ -1,64 +1,64 @@ package Net::Google::Spreadsheets::Cell; use Moose; extends 'Net::Google::Spreadsheets::Base'; has row => ( isa => 'Int', is => 'ro', ); has col => ( isa => 'Int', is => 'ro', ); has input_value => ( isa => 'Str', is => 'rw', trigger => sub {$_[0]->update}, ); after _update_atom => sub { my ($self) = @_; my ($elem) = $self->atom->elem->getElementsByTagNameNS($self->gs->{uri}, 'cell'); $self->{row} = $elem->getAttribute('row'); $self->{col} = $elem->getAttribute('col'); $self->{input_value} = $elem->getAttribute('inputValue'); $self->{content} = $elem->textContent || ''; }; around entry => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->gs, 'cell', '', { row => $self->row, col => $self->col, inputValue => $self->input_value, } ); my $link = XML::Atom::Link->new; $link->rel('edit'); $link->type('application/atom+xml'); $link->href($self->editurl); $entry->link($link); $entry->id($self->id); return $entry; }; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Cell - A representation class for Google Spreadsheet cell. -=head1 SYNOPSYS +=head1 SYNOPSIS =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Row.pm b/lib/Net/Google/Spreadsheets/Row.pm index 51cd899..138b2c7 100644 --- a/lib/Net/Google/Spreadsheets/Row.pm +++ b/lib/Net/Google/Spreadsheets/Row.pm @@ -1,43 +1,43 @@ package Net::Google::Spreadsheets::Row; use Moose; extends 'Net::Google::Spreadsheets::Base'; has +content => ( isa => 'HashRef', is => 'rw', default => sub { +{} }, trigger => sub {$_[0]->update}, ); after _update_atom => sub { my ($self) = @_; for my $node ($self->atom->elem->getElementsByTagNameNS($self->gsx->{uri}, '*')) { $self->{content}->{$node->localname} = $node->textContent; } }; around entry => sub { my ($next, $self) = @_; my $entry = $next->($self); while (my ($key, $value) = each %{$self->{content}}) { $entry->set($self->gsx, $key, $value); } return $entry; }; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Row - A representation class for Google Spreadsheet row. -=head1 SYNOPSYS +=head1 SYNOPSIS =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Spreadsheet.pm b/lib/Net/Google/Spreadsheets/Spreadsheet.pm index 74e746e..92be2d3 100644 --- a/lib/Net/Google/Spreadsheets/Spreadsheet.pm +++ b/lib/Net/Google/Spreadsheets/Spreadsheet.pm @@ -1,59 +1,59 @@ package Net::Google::Spreadsheets::Spreadsheet; use Moose; use XML::Atom; use Net::Google::Spreadsheets::Worksheet; use Path::Class; extends 'Net::Google::Spreadsheets::Base'; has +title => ( is => 'ro', ); has key => ( isa => 'Str', is => 'ro', required => 1, lazy => 1, default => sub { my $self = shift; my $key = file(URI->new($self->id)->path)->basename; return $key; } ); after _update_atom => sub { my ($self) = @_; $self->{content} = $self->atom->content->elem->getAttribute('src'); }; sub worksheets { my ($self, $cond) = @_; return $self->list_contents('Net::Google::Spreadsheets::Worksheet', $cond); } sub add_worksheet { my ($self, $args) = @_; my $entry = Net::Google::Spreadsheets::Worksheet->new->entry; my $atom = $self->service->post($self->content, $entry); $self->sync; return Net::Google::Spreadsheets::Worksheet->new( container => $self, atom => $atom, ); } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Spreadsheet - Representation of spreadsheet -=head1 SYNOPSYS +=head1 SYNOPSIS =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Worksheet.pm b/lib/Net/Google/Spreadsheets/Worksheet.pm index f529fe8..0132075 100644 --- a/lib/Net/Google/Spreadsheets/Worksheet.pm +++ b/lib/Net/Google/Spreadsheets/Worksheet.pm @@ -1,112 +1,112 @@ package Net::Google::Spreadsheets::Worksheet; use Moose; use Net::Google::Spreadsheets::Row; use Net::Google::Spreadsheets::Cell; extends 'Net::Google::Spreadsheets::Base'; has row_count => ( isa => 'Int', is => 'rw', default => 100, trigger => sub {$_[0]->update} ); has col_count => ( isa => 'Int', is => 'rw', default => 20, trigger => sub {$_[0]->update} ); has cellsfeed => ( isa => 'Str', is => 'ro', ); around entry => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->gs, 'rowCount', $self->row_count); $entry->set($self->gs, 'colCount', $self->col_count); return $entry; }; after _update_atom => sub { my ($self) = @_; $self->{content} = $self->atom->content->elem->getAttribute('src'); ($self->{cellsfeed}) = map {$_->href} grep { $_->rel eq 'http://schemas.google.com/spreadsheets/2006#cellsfeed' } $self->atom->link; $self->{row_count} = $self->atom->get($self->gs, 'rowCount'); $self->{col_count} = $self->atom->get($self->gs, 'colCount'); }; sub rows { my ($self, $cond) = @_; return $self->list_contents('Net::Google::Spreadsheets::Row', $cond); } sub cell { my ($self, $row, $col) = @_; $self->cellsfeed or return; my $url = sprintf "%s/R%sC%s", $self->cellsfeed, $row, $col; return Net::Google::Spreadsheets::Cell->new( container => $self, atom => $self->service->entry($url), ); } sub batchupdate_cell { my ($self, @args) = @_; my $feed = XML::Atom::Feed->new; for ( @args ) { my $id = sprintf("%s/R%sC%s",$self->cellsfeed, $_->{row}, $_->{col}); $_->{id} = $id; $_->{editurl} = $id; my $entry = Net::Google::Spreadsheets::Cell->new($_)->entry; $entry->set($self->batch, operation => '', {type => 'update'}); $entry->set($self->batch, id => $id); $feed->add_entry($entry); } my $res_feed = $self->service->post($self->cellsfeed."/batch", $feed, {'If-Match' => '*'}); $self->sync; return map { Net::Google::Spreadsheets::Cell->new( atom => $_, container => $self, ) } grep { my ($node) = $_->elem->getElementsByTagNameNS($self->batch->{uri}, 'status'); $node->getAttribute('code') == 200; } $res_feed->entries; } sub insert_row { my ($self, $args) = @_; my $entry = Net::Google::Spreadsheets::Row->new( content => $args, )->entry; my $atom = $self->service->post($self->content, $entry); $self->sync; return Net::Google::Spreadsheets::Row->new( container => $self, atom => $atom, ); } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Worksheet - Representation of worksheet. -=head1 SYNOPSYS +=head1 SYNOPSIS =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/xt/01_podspell.t b/xt/01_podspell.t index c162722..e37cfef 100644 --- a/xt/01_podspell.t +++ b/xt/01_podspell.t @@ -1,10 +1,11 @@ use Test::More; eval q{ use Test::Spelling }; plan skip_all => "Test::Spelling is not installed." if $@; add_stopwords(map { split /[\s\:\-]/ } <DATA>); $ENV{LANG} = 'C'; all_pod_files_spelling_ok('lib'); __DATA__ Nobuo Danjou [email protected] Net::Google::Spreadsheets +API
lopnor/Net-Google-Spreadsheets
c907e7495562ada5b2a9f572e2711574abbf1c3e
refactoring
diff --git a/lib/Net/Google/Spreadsheets/Cell.pm b/lib/Net/Google/Spreadsheets/Cell.pm index d1d4f82..8f0b395 100644 --- a/lib/Net/Google/Spreadsheets/Cell.pm +++ b/lib/Net/Google/Spreadsheets/Cell.pm @@ -1,64 +1,64 @@ package Net::Google::Spreadsheets::Cell; use Moose; extends 'Net::Google::Spreadsheets::Base'; has row => ( isa => 'Int', is => 'ro', ); has col => ( isa => 'Int', is => 'ro', ); has input_value => ( isa => 'Str', is => 'rw', trigger => sub {$_[0]->update}, ); after _update_atom => sub { my ($self) = @_; - my ($elem) = $self->atom->elem->getChildrenByTagNameNS($self->gs->{uri}, 'cell'); + my ($elem) = $self->atom->elem->getElementsByTagNameNS($self->gs->{uri}, 'cell'); $self->{row} = $elem->getAttribute('row'); $self->{col} = $elem->getAttribute('col'); $self->{input_value} = $elem->getAttribute('inputValue'); $self->{content} = $elem->textContent || ''; }; around entry => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->gs, 'cell', '', { row => $self->row, col => $self->col, inputValue => $self->input_value, } ); my $link = XML::Atom::Link->new; $link->rel('edit'); $link->type('application/atom+xml'); $link->href($self->editurl); $entry->link($link); $entry->id($self->id); return $entry; }; 1; __END__ =head1 NAME Net::Google::Spreadsheets::Cell - A representation class for Google Spreadsheet cell. =head1 SYNOPSYS =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Row.pm b/lib/Net/Google/Spreadsheets/Row.pm index 4c29bfa..51cd899 100644 --- a/lib/Net/Google/Spreadsheets/Row.pm +++ b/lib/Net/Google/Spreadsheets/Row.pm @@ -1,20 +1,43 @@ package Net::Google::Spreadsheets::Row; use Moose; extends 'Net::Google::Spreadsheets::Base'; +has +content => ( + isa => 'HashRef', + is => 'rw', + default => sub { +{} }, + trigger => sub {$_[0]->update}, +); + +after _update_atom => sub { + my ($self) = @_; + for my $node ($self->atom->elem->getElementsByTagNameNS($self->gsx->{uri}, '*')) { + $self->{content}->{$node->localname} = $node->textContent; + } +}; + +around entry => sub { + my ($next, $self) = @_; + my $entry = $next->($self); + while (my ($key, $value) = each %{$self->{content}}) { + $entry->set($self->gsx, $key, $value); + } + return $entry; +}; + 1; __END__ =head1 NAME Net::Google::Spreadsheets::Row - A representation class for Google Spreadsheet row. =head1 SYNOPSYS =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Spreadsheet.pm b/lib/Net/Google/Spreadsheets/Spreadsheet.pm index b32655a..74e746e 100644 --- a/lib/Net/Google/Spreadsheets/Spreadsheet.pm +++ b/lib/Net/Google/Spreadsheets/Spreadsheet.pm @@ -1,83 +1,59 @@ package Net::Google::Spreadsheets::Spreadsheet; use Moose; use XML::Atom; use Net::Google::Spreadsheets::Worksheet; use Path::Class; extends 'Net::Google::Spreadsheets::Base'; has +title => ( is => 'ro', ); -has worksheets => ( - isa => 'ArrayRef[Net::Google::Spreadsheets::Worksheet]', - is => 'rw', - weaken => 1, - default => sub { return [] }, -); - has key => ( isa => 'Str', is => 'ro', required => 1, lazy => 1, default => sub { my $self = shift; my $key = file(URI->new($self->id)->path)->basename; return $key; } ); after _update_atom => sub { my ($self) = @_; $self->{content} = $self->atom->content->elem->getAttribute('src'); - my $feed = $self->service->feed($self->content); - my @new_ws; - for my $entry ($feed->entries) { - my $ws = Net::Google::Spreadsheets::Worksheet->new( - container => $self, - atom => $entry, - ); - push @new_ws, $ws; - if (my ($orig) = grep {$_->id eq $ws->id} @{$self->worksheets}) { - $orig->atom($entry) if $orig->etag ne $ws->etag; - } else { - push @{$self->worksheets}, $ws; - } - } - $self->worksheets([ grep {my $ws = $_; grep {$ws->id eq $_->id} @new_ws} @{$self->worksheets} ]); }; +sub worksheets { + my ($self, $cond) = @_; + return $self->list_contents('Net::Google::Spreadsheets::Worksheet', $cond); +} sub add_worksheet { my ($self, $args) = @_; - my $title = $args->{title} - || "Sheet".(scalar @{$self->worksheets} + 1); - my $entry = XML::Atom::Entry->new; - $entry->title($title); - $entry->set($self->gs, 'colCount', 20); - $entry->set($self->gs, 'rowCount', 100); + my $entry = Net::Google::Spreadsheets::Worksheet->new->entry; my $atom = $self->service->post($self->content, $entry); - my $ws = Net::Google::Spreadsheets::Worksheet->new( + $self->sync; + return Net::Google::Spreadsheets::Worksheet->new( container => $self, atom => $atom, ); - push @{$self->worksheets}, $ws; - return $ws; } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Spreadsheet - Representation of spreadsheet =head1 SYNOPSYS =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/lib/Net/Google/Spreadsheets/Worksheet.pm b/lib/Net/Google/Spreadsheets/Worksheet.pm index 63b6c20..f529fe8 100644 --- a/lib/Net/Google/Spreadsheets/Worksheet.pm +++ b/lib/Net/Google/Spreadsheets/Worksheet.pm @@ -1,117 +1,112 @@ package Net::Google::Spreadsheets::Worksheet; use Moose; use Net::Google::Spreadsheets::Row; use Net::Google::Spreadsheets::Cell; extends 'Net::Google::Spreadsheets::Base'; has row_count => ( isa => 'Int', is => 'rw', default => 100, trigger => sub {$_[0]->update} ); has col_count => ( isa => 'Int', is => 'rw', default => 20, trigger => sub {$_[0]->update} ); has cellsfeed => ( isa => 'Str', is => 'ro', ); around entry => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->gs, 'rowCount', $self->row_count); $entry->set($self->gs, 'colCount', $self->col_count); return $entry; }; after _update_atom => sub { my ($self) = @_; $self->{content} = $self->atom->content->elem->getAttribute('src'); ($self->{cellsfeed}) = map {$_->href} grep { $_->rel eq 'http://schemas.google.com/spreadsheets/2006#cellsfeed' } $self->atom->link; $self->{row_count} = $self->atom->get($self->gs, 'rowCount'); $self->{col_count} = $self->atom->get($self->gs, 'colCount'); }; sub rows { my ($self, $cond) = @_; return $self->list_contents('Net::Google::Spreadsheets::Row', $cond); } sub cell { my ($self, $row, $col) = @_; $self->cellsfeed or return; my $url = sprintf "%s/R%sC%s", $self->cellsfeed, $row, $col; return Net::Google::Spreadsheets::Cell->new( container => $self, atom => $self->service->entry($url), ); } sub batchupdate_cell { my ($self, @args) = @_; my $feed = XML::Atom::Feed->new; for ( @args ) { my $id = sprintf("%s/R%sC%s",$self->cellsfeed, $_->{row}, $_->{col}); - my $entry = Net::Google::Spreadsheets::Cell->new( - id => $id, - editurl => $id, - row => $_->{row}, - col => $_->{col}, - input_value => $_->{input_value}, - )->entry; + $_->{id} = $id; + $_->{editurl} = $id; + my $entry = Net::Google::Spreadsheets::Cell->new($_)->entry; $entry->set($self->batch, operation => '', {type => 'update'}); $entry->set($self->batch, id => $id); $feed->add_entry($entry); } my $res_feed = $self->service->post($self->cellsfeed."/batch", $feed, {'If-Match' => '*'}); $self->sync; return map { Net::Google::Spreadsheets::Cell->new( atom => $_, container => $self, ) } grep { - my ($node) = $_->elem->getChildrenByTagNameNS($self->batch->{uri}, 'status'); + my ($node) = $_->elem->getElementsByTagNameNS($self->batch->{uri}, 'status'); $node->getAttribute('code') == 200; } $res_feed->entries; } sub insert_row { my ($self, $args) = @_; - my $entry = XML::Atom::Entry->new; - while (my ($key, $value) = each %{$args}) { - $entry->set($self->gsx, $key, $value); - } + my $entry = Net::Google::Spreadsheets::Row->new( + content => $args, + )->entry; my $atom = $self->service->post($self->content, $entry); $self->sync; return Net::Google::Spreadsheets::Row->new( container => $self, atom => $atom, ); } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Worksheet - Representation of worksheet. =head1 SYNOPSYS =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/t/04_worksheet.t b/t/04_worksheet.t index a3cfcc4..3c24d61 100644 --- a/t/04_worksheet.t +++ b/t/04_worksheet.t @@ -1,71 +1,71 @@ use strict; use Test::More; use Net::Google::Spreadsheets; my $ss; BEGIN { plan skip_all => 'set TEST_NET_GOOGLE_SPREADSHEETS to run this test' unless $ENV{TEST_NET_GOOGLE_SPREADSHEETS}; eval "use Config::Pit"; plan skip_all => 'This Test needs Config::Pit.' if $@; my $config = pit_get('google.com', require => { 'username' => 'your username', 'password' => 'your password', } ); my $service = Net::Google::Spreadsheets->new( username => $config->{username}, password => $config->{password}, ); my $title = 'test for Net::Google::Spreadsheets'; $ss = $service->spreadsheet({title => $title}); plan skip_all => "test spreadsheet '$title' doesn't exist." unless $ss; plan tests => 18; } { - my $ws = $ss->worksheets->[0]; + my ($ws) = $ss->worksheets; isa_ok $ws, 'Net::Google::Spreadsheets::Worksheet'; } { - my $before = scalar @{$ss->worksheets}; + my $before = scalar $ss->worksheets; my $ws = $ss->add_worksheet; isa_ok $ws, 'Net::Google::Spreadsheets::Worksheet'; - is scalar @{$ss->worksheets}, $before + 1; - ok grep {$_ == $ws} @{$ss->worksheets}; + is scalar $ss->worksheets, $before + 1; + ok grep {$_->id eq $ws->id} $ss->worksheets; } { - my $ws = $ss->worksheets->[-1]; + my $ws = ($ss->worksheets)[-1]; my $title = $ws->title . '+add'; is $ws->title($title), $title; is $ws->atom->title, $title; is $ws->title, $title; } { - my $ws = $ss->worksheets->[-1]; + my $ws = ($ss->worksheets)[-1]; my $etag_before = $ws->etag; my $before = $ws->col_count; my $col_count = $before + 1; is $ws->col_count($col_count), $col_count; is $ws->atom->get($ws->gs, 'colCount'), $col_count; is $ws->col_count, $col_count; isnt $ws->etag, $etag_before; } { - my $ws = $ss->worksheets->[-1]; + my $ws = ($ss->worksheets)[-1]; my $ss_etag_before = $ss->etag; my $etag_before = $ws->etag; my $before = $ws->row_count; my $row_count = $before + 1; is $ws->row_count($row_count), $row_count; is $ws->atom->get($ws->gs, 'rowCount'), $row_count; is $ws->row_count, $row_count; isnt $ws->etag, $etag_before; } { - my $before = scalar @{$ss->worksheets}; - my $ws = $ss->worksheets->[-1]; + my $before = scalar $ss->worksheets; + my $ws = ($ss->worksheets)[-1]; ok $ws->delete; - is scalar @{$ss->worksheets}, $before - 1; - ok ! grep {$_ == $ws} @{$ss->worksheets}; + is scalar $ss->worksheets, $before - 1; + ok ! grep {$_ == $ws} $ss->worksheets; } diff --git a/t/06_rows.t b/t/06_rows.t index 513c17f..200e8e9 100644 --- a/t/06_rows.t +++ b/t/06_rows.t @@ -1,49 +1,55 @@ use strict; use Test::More; use Net::Google::Spreadsheets; my $ws; BEGIN { plan skip_all => 'set TEST_NET_GOOGLE_SPREADSHEETS to run this test' unless $ENV{TEST_NET_GOOGLE_SPREADSHEETS}; eval "use Config::Pit"; plan skip_all => 'This Test needs Config::Pit.' if $@; my $config = pit_get('google.com', require => { 'username' => 'your username', 'password' => 'your password', } ); my $service = Net::Google::Spreadsheets->new( username => $config->{username}, password => $config->{password}, ); my $title = 'test for Net::Google::Spreadsheets'; my $ss = $service->spreadsheet({title => $title}); plan skip_all => "test spreadsheet '$title' doesn't exist." unless $ss; - plan tests => 6; + plan tests => 8; $ws = $ss->add_worksheet; } { is scalar $ws->rows, 0; $ws->batchupdate_cell( {col => 1, row => 1, input_value => 'name'}, {col => 2, row => 1, input_value => 'mail'}, {col => 3, row => 1, input_value => 'nick'}, ); is scalar $ws->rows, 0; - my $row = $ws->insert_row( - { - name => 'Nobuo Danjou', - mail => '[email protected]', - nick => 'lopnor', - } - ); + my $value = { + name => 'Nobuo Danjou', + mail => '[email protected]', + nick => 'lopnor', + }; + my $row = $ws->insert_row($value); isa_ok $row, 'Net::Google::Spreadsheets::Row'; + is_deeply $row->content, $value; + my $value2 = { + name => 'Kazuhiro Osawa', + nick => 'yappo', + }; + $row->content($value2); + is_deeply $row->content, $value2; is scalar $ws->rows, 1; ok $row->delete; is scalar $ws->rows, 0; } END { $ws->delete; }
lopnor/Net-Google-Spreadsheets
30c36b3c43d7033a86ea2eca1808d9877ac87fb4
row manipulation basics
diff --git a/t/06_rows.t b/t/06_rows.t index 249d438..513c17f 100644 --- a/t/06_rows.t +++ b/t/06_rows.t @@ -1,29 +1,49 @@ use strict; use Test::More; use Net::Google::Spreadsheets; my $ws; BEGIN { plan skip_all => 'set TEST_NET_GOOGLE_SPREADSHEETS to run this test' unless $ENV{TEST_NET_GOOGLE_SPREADSHEETS}; eval "use Config::Pit"; plan skip_all => 'This Test needs Config::Pit.' if $@; my $config = pit_get('google.com', require => { 'username' => 'your username', 'password' => 'your password', } ); my $service = Net::Google::Spreadsheets->new( username => $config->{username}, password => $config->{password}, ); my $title = 'test for Net::Google::Spreadsheets'; my $ss = $service->spreadsheet({title => $title}); plan skip_all => "test spreadsheet '$title' doesn't exist." unless $ss; - plan tests => 1; + plan tests => 6; $ws = $ss->add_worksheet; } +{ + is scalar $ws->rows, 0; + $ws->batchupdate_cell( + {col => 1, row => 1, input_value => 'name'}, + {col => 2, row => 1, input_value => 'mail'}, + {col => 3, row => 1, input_value => 'nick'}, + ); + is scalar $ws->rows, 0; + my $row = $ws->insert_row( + { + name => 'Nobuo Danjou', + mail => '[email protected]', + nick => 'lopnor', + } + ); + isa_ok $row, 'Net::Google::Spreadsheets::Row'; + is scalar $ws->rows, 1; + ok $row->delete; + is scalar $ws->rows, 0; +} END { $ws->delete; }
lopnor/Net-Google-Spreadsheets
522b5130f302621b9e4a52ed5d62ba8a5917979d
cell manipulations
diff --git a/MANIFEST b/MANIFEST index 992a9ae..486ae99 100644 --- a/MANIFEST +++ b/MANIFEST @@ -1,36 +1,38 @@ Changes inc/Module/Install.pm inc/Module/Install/AuthorTests.pm inc/Module/Install/Base.pm inc/Module/Install/Can.pm inc/Module/Install/Fetch.pm inc/Module/Install/Include.pm inc/Module/Install/Makefile.pm inc/Module/Install/Metadata.pm inc/Module/Install/TestBase.pm inc/Module/Install/Win32.pm inc/Module/Install/WriteAll.pm inc/Spiffy.pm inc/Test/Base.pm inc/Test/Base/Filter.pm inc/Test/Builder.pm inc/Test/Builder/Module.pm inc/Test/More.pm lib/Net/Google/Spreadsheets.pm lib/Net/Google/Spreadsheets/Base.pm +lib/Net/Google/Spreadsheets/Cell.pm +lib/Net/Google/Spreadsheets/Row.pm lib/Net/Google/Spreadsheets/Spreadsheet.pm lib/Net/Google/Spreadsheets/Worksheet.pm Makefile.PL MANIFEST This list of files META.yml README t/00_compile.t t/01_instanciate.t t/02_spreadsheets.t t/03_spreadsheet.t t/04_worksheet.t t/05_rows.t xt/01_podspell.t xt/02_perlcritic.t xt/03_pod.t xt/perlcriticrc diff --git a/lib/Net/Google/Spreadsheets.pm b/lib/Net/Google/Spreadsheets.pm index 6c33885..187a940 100644 --- a/lib/Net/Google/Spreadsheets.pm +++ b/lib/Net/Google/Spreadsheets.pm @@ -1,246 +1,244 @@ package Net::Google::Spreadsheets; use Moose; use Carp; use Net::Google::AuthSub; use Net::Google::Spreadsheets::Spreadsheet; use LWP::UserAgent; use XML::Atom; use XML::Atom::Feed; use URI; use HTTP::Headers; our $VERSION = '0.01'; BEGIN { $XML::Atom::DefaultVersion = 1; } has username => ( isa => 'Str', is => 'ro', required => 1 ); has password => ( isa => 'Str', is => 'ro', required => 1 ); has source => ( isa => 'Str', is => 'ro', required => 1, default => sub { __PACKAGE__.'-'.$VERSION }, ); has auth => ( isa => 'Str', is => 'rw', required => 1, lazy => 1, default => sub { my $self = shift; my $authsub = Net::Google::AuthSub->new( service => 'wise', source => $self->source, ); my $res = $authsub->login( $self->username, $self->password, ); $res->is_success or return; return $res->auth; }, ); has host => ( isa => 'Str', is => 'ro', required => 1, default => 'spreadsheets.google.com', ); has ua => ( isa => 'LWP::UserAgent', is => 'ro', required => 1, lazy => 1, default => sub { my $self = shift; my $ua = LWP::UserAgent->new( agent => $self->source, ); $ua->default_headers( HTTP::Headers->new( Authorization => sprintf('GoogleLogin auth=%s', $self->auth), GData_Version => 2, ) ); return $ua; } ); sub spreadsheets { my ($self, $cond) = @_; my $feed = $self->feed( sprintf ('http://%s/feeds/spreadsheets/private/full', $self->host), $cond ); return [ map { Net::Google::Spreadsheets::Spreadsheet->new( atom => $_, service => $self, ) } $feed->entries ]; } sub spreadsheet { my ($self, $args) = @_; my $url = sprintf('http://%s/feeds/spreadsheets/', $self->host); my $cond = $args->{title} ? { title => $args->{title}, 'title-exact' => 'true' } : {}; my $feed = $self->feed( $url."private/full", $cond ); my $entry; for ( $feed->entries ) { my ($key) = $_->id =~ m{^$url(.+)$}; $entry = $_ and last if $args->{title} && $_->title eq $args->{title}; $entry = $_ and last if $args->{key} && $key eq $args->{key}; } $entry or return; return Net::Google::Spreadsheets::Spreadsheet->new( atom => $entry, service => $self, ); } sub request { my ($self, $args) = @_; my $method = delete $args->{method}; $method ||= $args->{content} ? 'POST' : 'GET'; my $uri = URI->new($args->{'uri'}); $uri->query_form($args->{query}) if $args->{query}; my $req = HTTP::Request->new($method => "$uri"); $req->content($args->{content}) if $args->{content}; $req->header('Content-Type' => $args->{content_type}) if $args->{content_type}; if ($args->{header}) { while (my @pair = each %{$args->{header}}) { $req->header(@pair); } } my $res = $self->ua->request($req); # warn $res->request->as_string; # warn $res->as_string; unless ($res->is_success) { warn $res->request->as_string; warn $res->as_string; croak "request failed: ",$res->code; } return $res; } sub feed { my ($self, $url, $query) = @_; my $res = $self->request( { uri => $url, query => $query || undef, } ); return XML::Atom::Feed->new(\($res->content)); } sub entry { my ($self, $url, $query) = @_; my $res = $self->request( { uri => $url, query => $query || undef, } ); return XML::Atom::Entry->new(\($res->content)); } sub post { - my ($self, $url, $entry, $query) = @_; + my ($self, $url, $entry, $header) = @_; my $res = $self->request( { uri => $url, - query => $query || undef, content => $entry->as_xml, + header => $header || undef, content_type => 'application/atom+xml', } ); - return XML::Atom::Entry->new(\($res->content)); + return (ref $entry)->new(\($res->content)); +# return XML::Atom::Entry->new(\($res->content)); } sub put { my ($self, $args) = @_; my $res = $self->request( { method => 'PUT', uri => $args->{self}->editurl, content => $args->{entry}->as_xml, - header => {'If-Match' => $args->{self}->etag}, + header => {'If-Match' => $args->{self}->etag }, content_type => 'application/atom+xml', } ); return XML::Atom::Entry->new(\($res->content)); } 1; __END__ =head1 NAME Net::Google::Spreadsheets - A Perl module for using Google Spreadsheets API. =head1 SYNOPSIS use Net::Google::Spreadsheets; - my $api = Net::Google::Spreadsheets->new; - my $res = $api->login( - { - username => '[email protected]', - password => 'mypassword' - } + my $service = Net::Google::Spreadsheets->new( + username => '[email protected]', + password => 'mypassword' ); - my @spreadsheets = $api->list(); + my @spreadsheets = $service->spreadsheets(); - my $spreadsheet = $api->spreadsheet('pZV-pns_sm9PtH2WowhU2Ew'); + my $spreadsheet = $api->spreadsheet({key => 'pZV-pns_sm9PtH2WowhU2Ew'}); my $worksheet = $spreadsheet->worksheet(1); my @fields = $worksheet->fields(); my $inserted_row = $worksheet->insert( { name => 'danjou', } ); my @rows = $worksheet->rows; my $row = $worksheet->row(1); $row->update( { nick => 'lopnor', mail => '[email protected]', } ); =head1 DESCRIPTION Net::Google::Spreadsheets is a Perl module for using Google Spreadsheets API. =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =head1 SEE ALSO =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Net/Google/Spreadsheets/Base.pm b/lib/Net/Google/Spreadsheets/Base.pm index fefbebb..df77a39 100644 --- a/lib/Net/Google/Spreadsheets/Base.pm +++ b/lib/Net/Google/Spreadsheets/Base.pm @@ -1,140 +1,149 @@ package Net::Google::Spreadsheets::Base; use Moose; use Carp; use Moose::Util::TypeConstraints; use Net::Google::Spreadsheets::Base; has service => ( isa => 'Net::Google::Spreadsheets', is => 'ro', required => 1, lazy => 1, default => sub { shift->container->service }, ); my %ns = ( gd => 'http://schemas.google.com/g/2005', gs => 'http://schemas.google.com/spreadsheets/2006', gsx => 'http://schemas.google.com/spreadsheets/2006/extended', + batch => 'http://schemas.google.com/gdata/batch', ); while (my ($prefix, $uri) = each %ns) { has $prefix => ( isa => 'XML::Atom::Namespace', is => 'ro', required => 1, default => sub {XML::Atom::Namespace->new($prefix, $uri)}, ); } my %rel2label = ( edit => 'editurl', self => 'selfurl', ); for (values %rel2label) { has $_ => (isa => 'Str', is => 'ro'); } has atom => ( isa => 'XML::Atom::Entry', is => 'rw', trigger => sub { my ($self, $arg) = @_; my $id = $self->atom->get($self->atom->ns, 'id'); croak "can't set different id!" if $self->id && $self->id ne $id; $self->_update_atom; }, ); has id => ( isa => 'Str', is => 'rw', ); has content => ( isa => 'Str', - is => 'rw', + is => 'ro', ); has title => ( isa => 'Str', is => 'rw', default => 'untitled', trigger => sub {$_[0]->update} ); has author => ( isa => 'XML::Atom::Person', is => 'rw', ); has etag => ( isa => 'Str', is => 'rw', ); has container => ( isa => 'Maybe[Net::Google::Spreadsheets::Base]', is => 'ro', ); sub _update_atom { my ($self) = @_; $self->{title} = $self->atom->title; $self->{id} = $self->atom->get($self->atom->ns, 'id'); $self->{author} = $self->atom->author; $self->etag($self->atom->elem->getAttributeNS($self->gd->{uri}, 'etag')); for ($self->atom->link) { my $label = $rel2label{$_->rel} or next; $self->{$label} = $_->href; } } +sub list_contents { + my ($self, $class, $cond) = @_; + $self->content or return; + my $feed = $self->service->feed($self->content, $cond); + return map {$class->new(container => $self, atom => $_)} $feed->entries; +} + sub entry { my ($self) = @_; my $entry = XML::Atom::Entry->new; $entry->title($self->title) if $self->title; return $entry; } sub sync { my ($self) = @_; my $entry = $self->service->entry($self->selfurl); $self->atom($entry); } sub update { my ($self) = @_; + $self->etag or return; my $atom = $self->service->put( { self => $self, entry => $self->entry, } ); $self->container->sync; $self->atom($atom); } sub delete { my $self = shift; my $res = $self->service->request( { uri => $self->editurl, method => 'DELETE', header => {'If-Match' => $self->etag}, } ); $self->container->sync if $res->is_success; return $res->is_success; } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Base - Base class of Net::Google::Spreadsheets::*. =cut diff --git a/lib/Net/Google/Spreadsheets/Cell.pm b/lib/Net/Google/Spreadsheets/Cell.pm new file mode 100644 index 0000000..d1d4f82 --- /dev/null +++ b/lib/Net/Google/Spreadsheets/Cell.pm @@ -0,0 +1,64 @@ +package Net::Google::Spreadsheets::Cell; +use Moose; + +extends 'Net::Google::Spreadsheets::Base'; + +has row => ( + isa => 'Int', + is => 'ro', +); + +has col => ( + isa => 'Int', + is => 'ro', +); + +has input_value => ( + isa => 'Str', + is => 'rw', + trigger => sub {$_[0]->update}, +); + +after _update_atom => sub { + my ($self) = @_; + my ($elem) = $self->atom->elem->getChildrenByTagNameNS($self->gs->{uri}, 'cell'); + $self->{row} = $elem->getAttribute('row'); + $self->{col} = $elem->getAttribute('col'); + $self->{input_value} = $elem->getAttribute('inputValue'); + $self->{content} = $elem->textContent || ''; +}; + +around entry => sub { + my ($next, $self) = @_; + my $entry = $next->($self); + $entry->set($self->gs, 'cell', '', + { + row => $self->row, + col => $self->col, + inputValue => $self->input_value, + } + ); + my $link = XML::Atom::Link->new; + $link->rel('edit'); + $link->type('application/atom+xml'); + $link->href($self->editurl); + $entry->link($link); + $entry->id($self->id); + return $entry; +}; + +1; +__END__ + +=head1 NAME + +Net::Google::Spreadsheets::Cell - A representation class for Google Spreadsheet cell. + +=head1 SYNOPSYS + +=head1 AUTHOR + +Nobuo Danjou E<lt>[email protected]<gt> + +=cut + diff --git a/lib/Net/Google/Spreadsheets/Row.pm b/lib/Net/Google/Spreadsheets/Row.pm new file mode 100644 index 0000000..4c29bfa --- /dev/null +++ b/lib/Net/Google/Spreadsheets/Row.pm @@ -0,0 +1,20 @@ +package Net::Google::Spreadsheets::Row; +use Moose; + +extends 'Net::Google::Spreadsheets::Base'; + +1; +__END__ + +=head1 NAME + +Net::Google::Spreadsheets::Row - A representation class for Google Spreadsheet row. + +=head1 SYNOPSYS + +=head1 AUTHOR + +Nobuo Danjou E<lt>[email protected]<gt> + +=cut + diff --git a/lib/Net/Google/Spreadsheets/Worksheet.pm b/lib/Net/Google/Spreadsheets/Worksheet.pm index 2245b61..63b6c20 100644 --- a/lib/Net/Google/Spreadsheets/Worksheet.pm +++ b/lib/Net/Google/Spreadsheets/Worksheet.pm @@ -1,47 +1,117 @@ package Net::Google::Spreadsheets::Worksheet; use Moose; +use Net::Google::Spreadsheets::Row; +use Net::Google::Spreadsheets::Cell; extends 'Net::Google::Spreadsheets::Base'; has row_count => ( isa => 'Int', is => 'rw', default => 100, trigger => sub {$_[0]->update} ); has col_count => ( isa => 'Int', is => 'rw', default => 20, trigger => sub {$_[0]->update} ); +has cellsfeed => ( + isa => 'Str', + is => 'ro', +); + around entry => sub { my ($next, $self) = @_; my $entry = $next->($self); $entry->set($self->gs, 'rowCount', $self->row_count); $entry->set($self->gs, 'colCount', $self->col_count); return $entry; }; after _update_atom => sub { my ($self) = @_; + $self->{content} = $self->atom->content->elem->getAttribute('src'); + ($self->{cellsfeed}) = map {$_->href} grep { + $_->rel eq 'http://schemas.google.com/spreadsheets/2006#cellsfeed' + } $self->atom->link; $self->{row_count} = $self->atom->get($self->gs, 'rowCount'); $self->{col_count} = $self->atom->get($self->gs, 'colCount'); }; + +sub rows { + my ($self, $cond) = @_; + return $self->list_contents('Net::Google::Spreadsheets::Row', $cond); +} + +sub cell { + my ($self, $row, $col) = @_; + $self->cellsfeed or return; + my $url = sprintf "%s/R%sC%s", $self->cellsfeed, $row, $col; + return Net::Google::Spreadsheets::Cell->new( + container => $self, + atom => $self->service->entry($url), + ); +} + +sub batchupdate_cell { + my ($self, @args) = @_; + my $feed = XML::Atom::Feed->new; + for ( @args ) { + my $id = sprintf("%s/R%sC%s",$self->cellsfeed, $_->{row}, $_->{col}); + my $entry = Net::Google::Spreadsheets::Cell->new( + id => $id, + editurl => $id, + row => $_->{row}, + col => $_->{col}, + input_value => $_->{input_value}, + )->entry; + $entry->set($self->batch, operation => '', {type => 'update'}); + $entry->set($self->batch, id => $id); + $feed->add_entry($entry); + } + my $res_feed = $self->service->post($self->cellsfeed."/batch", $feed, {'If-Match' => '*'}); + $self->sync; + return map { + Net::Google::Spreadsheets::Cell->new( + atom => $_, + container => $self, + ) + } grep { + my ($node) = $_->elem->getChildrenByTagNameNS($self->batch->{uri}, 'status'); + $node->getAttribute('code') == 200; + } $res_feed->entries; +} + +sub insert_row { + my ($self, $args) = @_; + my $entry = XML::Atom::Entry->new; + while (my ($key, $value) = each %{$args}) { + $entry->set($self->gsx, $key, $value); + } + my $atom = $self->service->post($self->content, $entry); + $self->sync; + return Net::Google::Spreadsheets::Row->new( + container => $self, + atom => $atom, + ); +} + 1; __END__ =head1 NAME Net::Google::Spreadsheets::Worksheet - Representation of worksheet. =head1 SYNOPSYS =head1 AUTHOR Nobuo Danjou E<lt>[email protected]<gt> =cut diff --git a/t/05_cell.t b/t/05_cell.t new file mode 100644 index 0000000..d39df66 --- /dev/null +++ b/t/05_cell.t @@ -0,0 +1,59 @@ +use strict; +use Test::More; + +use Net::Google::Spreadsheets; + +my $ws; +BEGIN { + plan skip_all => 'set TEST_NET_GOOGLE_SPREADSHEETS to run this test' + unless $ENV{TEST_NET_GOOGLE_SPREADSHEETS}; + eval "use Config::Pit"; + plan skip_all => 'This Test needs Config::Pit.' if $@; + my $config = pit_get('google.com', require => { + 'username' => 'your username', + 'password' => 'your password', + } + ); + my $service = Net::Google::Spreadsheets->new( + username => $config->{username}, + password => $config->{password}, + ); + my $title = 'test for Net::Google::Spreadsheets'; + my $ss = $service->spreadsheet({title => $title}); + plan skip_all => "test spreadsheet '$title' doesn't exist." unless $ss; + plan tests => 11; + $ws = $ss->add_worksheet; +} +{ + my $value = 'first cell value'; + my $cell = $ws->cell(1,1); + isa_ok $cell, 'Net::Google::Spreadsheets::Cell'; + my $previous = $cell->content; + is $previous, ''; + ok $cell->input_value($value); + is $cell->content, $value; +} +{ + my $value = 'second cell value'; + my @cells = $ws->batchupdate_cell( + {row => 1, col => 1, input_value => $value} + ); + is scalar @cells, 1; + isa_ok $cells[0], 'Net::Google::Spreadsheets::Cell'; + is $cells[0]->content, $value; +} +{ + my $value1 = 'third cell value'; + my $value2 = 'fourth cell value'; + my @cells = $ws->batchupdate_cell( + {row => 1, col => 1, input_value => $value1}, + {row => 1, col => 2, input_value => $value2}, + ); + is scalar @cells, 2; + isa_ok $cells[0], 'Net::Google::Spreadsheets::Cell'; + ok grep {$_->col == 1 && $_->row == 1 && $_->content eq $value1} @cells; + ok grep {$_->col == 2 && $_->row == 1 && $_->content eq $value2} @cells; +} +END { + $ws->delete; +} diff --git a/t/05_rows.t b/t/06_rows.t similarity index 100% rename from t/05_rows.t rename to t/06_rows.t
lopnor/Net-Google-Spreadsheets
abbbac1e5a84eb17690b85162bbf7b17b0b84f3d
yet better tests, removed weak_ref attribute from service, container
diff --git a/lib/Net/Google/Spreadsheets/Base.pm b/lib/Net/Google/Spreadsheets/Base.pm index a591c0f..fefbebb 100644 --- a/lib/Net/Google/Spreadsheets/Base.pm +++ b/lib/Net/Google/Spreadsheets/Base.pm @@ -1,142 +1,140 @@ package Net::Google::Spreadsheets::Base; use Moose; use Carp; use Moose::Util::TypeConstraints; use Net::Google::Spreadsheets::Base; has service => ( isa => 'Net::Google::Spreadsheets', is => 'ro', required => 1, lazy => 1, default => sub { shift->container->service }, - weak_ref => 1, ); my %ns = ( gd => 'http://schemas.google.com/g/2005', gs => 'http://schemas.google.com/spreadsheets/2006', gsx => 'http://schemas.google.com/spreadsheets/2006/extended', ); while (my ($prefix, $uri) = each %ns) { has $prefix => ( isa => 'XML::Atom::Namespace', is => 'ro', required => 1, default => sub {XML::Atom::Namespace->new($prefix, $uri)}, ); } my %rel2label = ( edit => 'editurl', self => 'selfurl', ); for (values %rel2label) { has $_ => (isa => 'Str', is => 'ro'); } has atom => ( isa => 'XML::Atom::Entry', is => 'rw', trigger => sub { my ($self, $arg) = @_; my $id = $self->atom->get($self->atom->ns, 'id'); croak "can't set different id!" if $self->id && $self->id ne $id; $self->_update_atom; }, ); has id => ( isa => 'Str', is => 'rw', ); has content => ( isa => 'Str', is => 'rw', ); has title => ( isa => 'Str', is => 'rw', default => 'untitled', trigger => sub {$_[0]->update} ); has author => ( isa => 'XML::Atom::Person', is => 'rw', ); has etag => ( isa => 'Str', is => 'rw', ); has container => ( isa => 'Maybe[Net::Google::Spreadsheets::Base]', is => 'ro', - weak_ref => 1, ); sub _update_atom { my ($self) = @_; $self->{title} = $self->atom->title; $self->{id} = $self->atom->get($self->atom->ns, 'id'); $self->{author} = $self->atom->author; $self->etag($self->atom->elem->getAttributeNS($self->gd->{uri}, 'etag')); for ($self->atom->link) { my $label = $rel2label{$_->rel} or next; $self->{$label} = $_->href; } } sub entry { my ($self) = @_; my $entry = XML::Atom::Entry->new; $entry->title($self->title) if $self->title; return $entry; } sub sync { my ($self) = @_; my $entry = $self->service->entry($self->selfurl); $self->atom($entry); } sub update { my ($self) = @_; my $atom = $self->service->put( { self => $self, entry => $self->entry, } ); $self->container->sync; $self->atom($atom); } sub delete { my $self = shift; my $res = $self->service->request( { uri => $self->editurl, method => 'DELETE', header => {'If-Match' => $self->etag}, } ); $self->container->sync if $res->is_success; return $res->is_success; } 1; __END__ =head1 NAME Net::Google::Spreadsheets::Base - Base class of Net::Google::Spreadsheets::*. =cut diff --git a/t/02_spreadsheets.t b/t/02_spreadsheets.t index 29886f7..89a3f10 100644 --- a/t/02_spreadsheets.t +++ b/t/02_spreadsheets.t @@ -1,28 +1,29 @@ use strict; use Test::More; use Net::Google::Spreadsheets; my $service; BEGIN { plan skip_all => 'set TEST_NET_GOOGLE_SPREADSHEETS to run this test' unless $ENV{TEST_NET_GOOGLE_SPREADSHEETS}; eval "use Config::Pit"; plan skip_all => 'This Test needs Config::Pit.' if $@; my $config = pit_get('google.com', require => { 'username' => 'your username', 'password' => 'your password', } ); $service = Net::Google::Spreadsheets->new( username => $config->{username}, password => $config->{password}, ); my $title = 'test for Net::Google::Spreadsheets'; my $sheet = $service->spreadsheet({title => $title}); plan skip_all => "test spreadsheet '$title' doesn't exist." unless $sheet; plan tests => 1; } SKIP: { my $sheets = $service->spreadsheets; + ok scalar @$sheets; } diff --git a/t/03_spreadsheet.t b/t/03_spreadsheet.t index 9c99b5b..40d7c1b 100644 --- a/t/03_spreadsheet.t +++ b/t/03_spreadsheet.t @@ -1,54 +1,43 @@ use strict; use Test::More; use Net::Google::Spreadsheets; my ($service, $config); BEGIN { plan skip_all => 'set TEST_NET_GOOGLE_SPREADSHEETS to run this test' unless $ENV{TEST_NET_GOOGLE_SPREADSHEETS}; eval "use Config::Pit"; plan skip_all => 'This Test needs Config::Pit.' if $@; $config = pit_get('google.com', require => { 'username' => 'your username', 'password' => 'your password', } ); $service = Net::Google::Spreadsheets->new( username => $config->{username}, password => $config->{password}, ); my $title = 'test for Net::Google::Spreadsheets'; my $sheet = $service->spreadsheet({title => $title}); plan skip_all => "test spreadsheet '$title' doesn't exist." unless $sheet; - plan tests => 15; -} - -{ - ok $service->spreadsheets; + plan tests => 10; } { - my $title = 'test for Net::Google::Speradsheets'; + my $title = 'test for Net::Google::Spreadsheets'; my $ss = $service->spreadsheet({title => $title}); ok $ss; isa_ok $ss, 'Net::Google::Spreadsheets::Spreadsheet'; is $ss->title, $title; like $ss->id, qr{^http://spreadsheets.google.com/feeds/spreadsheets/}; isa_ok $ss->author, 'XML::Atom::Person'; is $ss->author->email, $config->{username}; my $key = $ss->key; ok length $key, 'key defined'; { my $ss2 = $service->spreadsheet({key => $key}); ok $ss2; isa_ok $ss2, 'Net::Google::Spreadsheets::Spreadsheet'; is $ss2->key, $key; } } -{ - my $title = 'test for Net::Google::Speradsheets'; - my $spreadsheet = $service->spreadsheet({ 'title' => $title }); - ok $spreadsheet; - isa_ok $spreadsheet, 'Net::Google::Spreadsheets::Spreadsheet'; - is $spreadsheet->title, $title; -} diff --git a/t/04_worksheet.t b/t/04_worksheet.t index c670dfc..a3cfcc4 100644 --- a/t/04_worksheet.t +++ b/t/04_worksheet.t @@ -1,71 +1,71 @@ use strict; use Test::More; use Net::Google::Spreadsheets; -my $service; +my $ss; BEGIN { plan skip_all => 'set TEST_NET_GOOGLE_SPREADSHEETS to run this test' unless $ENV{TEST_NET_GOOGLE_SPREADSHEETS}; eval "use Config::Pit"; plan skip_all => 'This Test needs Config::Pit.' if $@; my $config = pit_get('google.com', require => { 'username' => 'your username', 'password' => 'your password', } ); - $service = Net::Google::Spreadsheets->new( + my $service = Net::Google::Spreadsheets->new( username => $config->{username}, password => $config->{password}, ); my $title = 'test for Net::Google::Spreadsheets'; - my $sheet = $service->spreadsheet({title => $title}); - plan skip_all => "test spreadsheet '$title' doesn't exist." unless $sheet; + $ss = $service->spreadsheet({title => $title}); + plan skip_all => "test spreadsheet '$title' doesn't exist." unless $ss; plan tests => 18; } { - my $ws = $spreadsheet->worksheets->[0]; + my $ws = $ss->worksheets->[0]; isa_ok $ws, 'Net::Google::Spreadsheets::Worksheet'; } { - my $before = scalar @{$spreadsheet->worksheets}; - my $ws = $spreadsheet->add_worksheet; + my $before = scalar @{$ss->worksheets}; + my $ws = $ss->add_worksheet; isa_ok $ws, 'Net::Google::Spreadsheets::Worksheet'; - is scalar @{$spreadsheet->worksheets}, $before + 1; - ok grep {$_ == $ws} @{$spreadsheet->worksheets}; + is scalar @{$ss->worksheets}, $before + 1; + ok grep {$_ == $ws} @{$ss->worksheets}; } { - my $ws = $spreadsheet->worksheets->[-1]; + my $ws = $ss->worksheets->[-1]; my $title = $ws->title . '+add'; is $ws->title($title), $title; is $ws->atom->title, $title; is $ws->title, $title; } { - my $ws = $spreadsheet->worksheets->[-1]; + my $ws = $ss->worksheets->[-1]; my $etag_before = $ws->etag; my $before = $ws->col_count; my $col_count = $before + 1; is $ws->col_count($col_count), $col_count; is $ws->atom->get($ws->gs, 'colCount'), $col_count; is $ws->col_count, $col_count; isnt $ws->etag, $etag_before; } { - my $ws = $spreadsheet->worksheets->[-1]; - my $ss_etag_before = $spreadsheet->etag; + my $ws = $ss->worksheets->[-1]; + my $ss_etag_before = $ss->etag; my $etag_before = $ws->etag; my $before = $ws->row_count; my $row_count = $before + 1; is $ws->row_count($row_count), $row_count; is $ws->atom->get($ws->gs, 'rowCount'), $row_count; is $ws->row_count, $row_count; isnt $ws->etag, $etag_before; } { - my $before = scalar @{$spreadsheet->worksheets}; - my $ws = $spreadsheet->worksheets->[-1]; + my $before = scalar @{$ss->worksheets}; + my $ws = $ss->worksheets->[-1]; ok $ws->delete; - is scalar @{$spreadsheet->worksheets}, $before - 1; - ok ! grep {$_ == $ws} @{$spreadsheet->worksheets}; + is scalar @{$ss->worksheets}, $before - 1; + ok ! grep {$_ == $ws} @{$ss->worksheets}; } diff --git a/t/05_rows.t b/t/05_rows.t index d0f078e..249d438 100644 --- a/t/05_rows.t +++ b/t/05_rows.t @@ -1,27 +1,29 @@ use strict; use Test::More; use Net::Google::Spreadsheets; -my $sheet; +my $ws; BEGIN { plan skip_all => 'set TEST_NET_GOOGLE_SPREADSHEETS to run this test' unless $ENV{TEST_NET_GOOGLE_SPREADSHEETS}; eval "use Config::Pit"; plan skip_all => 'This Test needs Config::Pit.' if $@; my $config = pit_get('google.com', require => { 'username' => 'your username', 'password' => 'your password', } ); my $service = Net::Google::Spreadsheets->new( username => $config->{username}, password => $config->{password}, ); my $title = 'test for Net::Google::Spreadsheets'; - $sheet = $service->spreadsheet({title => $title}); - plan skip_all => "test spreadsheet '$title' doesn't exist." unless $sheet; + my $ss = $service->spreadsheet({title => $title}); + plan skip_all => "test spreadsheet '$title' doesn't exist." unless $ss; plan tests => 1; + $ws = $ss->add_worksheet; +} +END { + $ws->delete; } -my $ws = $sheet->worksheets->[0]; -isa_ok $ws, 'Net::Google::Spreadsheets::Worksheet';
Tigraine/git-cheatsheet-gadget
c1ff548cfa1e01b156128e4d82cc0170722c37dc
Added Acknowledgements and license.txt to root
diff --git a/acknowledgements.txt b/acknowledgements.txt new file mode 100644 index 0000000..ef1248c --- /dev/null +++ b/acknowledgements.txt @@ -0,0 +1,5 @@ +The image used in this gadget was created by Zack Rusin +http://zrusin.blogspot.com/2007/09/git-cheat-sheet.html + +The git logo was taken from the official git website: +http://git-scm.com/ \ No newline at end of file diff --git a/git-cheat.gadget b/git-cheatsheet.gadget similarity index 99% rename from git-cheat.gadget rename to git-cheatsheet.gadget index 775947d..77da221 100644 Binary files a/git-cheat.gadget and b/git-cheatsheet.gadget differ diff --git a/license.txt b/license.txt new file mode 100644 index 0000000..a83c658 --- /dev/null +++ b/license.txt @@ -0,0 +1,13 @@ +Copyright 2009 Daniel Hölbling + +Licensed under the Apache License, Version 2.0 (the License); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an AS IS BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file
Tigraine/git-cheatsheet-gadget
517f3169a6762b5748be344101abbbd1e55bb6b1
Added license.txt and acknowledgements.txt
diff --git a/src/acknowledgements.txt b/src/acknowledgements.txt new file mode 100644 index 0000000..ef1248c --- /dev/null +++ b/src/acknowledgements.txt @@ -0,0 +1,5 @@ +The image used in this gadget was created by Zack Rusin +http://zrusin.blogspot.com/2007/09/git-cheat-sheet.html + +The git logo was taken from the official git website: +http://git-scm.com/ \ No newline at end of file diff --git a/src/license.txt b/src/license.txt new file mode 100644 index 0000000..a83c658 --- /dev/null +++ b/src/license.txt @@ -0,0 +1,13 @@ +Copyright 2009 Daniel Hölbling + +Licensed under the Apache License, Version 2.0 (the License); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an AS IS BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file
Tigraine/git-cheatsheet-gadget
64dafd26637271effdbc98db6eb6a175abeb701f
Added final gadget build
diff --git a/git-cheat.gadget b/git-cheat.gadget new file mode 100644 index 0000000..775947d Binary files /dev/null and b/git-cheat.gadget differ
Tigraine/git-cheatsheet-gadget
e17cea94eb4cf228a622dbfb8a781f673a806f4d
Final gadget
diff --git a/src/gadget.xml b/src/gadget.xml index 8032f9b..9d904bb 100644 --- a/src/gadget.xml +++ b/src/gadget.xml @@ -1,23 +1,23 @@ -<?xml version="1.0" encoding="utf-8" ?> +<?xml version="1.0" encoding="utf-8" ?> <gadget> <name>git-cheatsheet</name> <namespace>windows.sdk</namespace> <version>1.0.0.0</version> - <author name="Daniel Hölbling"> + <author name="Daniel Hoelbling"> <info url="http://www.tigraine.at" /> <logo src="git-logo.png" /> </author> - <copyright>&#169; Daniel Hölbling.</copyright> + <copyright>&#169; Daniel Hoelbling.</copyright> <description>Displays a GIT cheatsheet on the Desktop.</description> <icons> <icon height="48" width="48" src="icon.png" /> </icons> <hosts> <host name="sidebar"> - <base type="HTML" apiVersion="1.0.0" src="sidebar.html" /> + <base type="HTML" apiVersion="1.0.0" src="git.html" /> <permissions>Full</permissions> <platform minPlatformVersion="1.0" /> <defaultImage src="git-logo.png" /> </host> </hosts> </gadget> \ No newline at end of file diff --git a/src/git-cheat-sheet-medium.png b/src/git-cheat-sheet-medium.png new file mode 100644 index 0000000..2d9ae45 Binary files /dev/null and b/src/git-cheat-sheet-medium.png differ diff --git a/src/git.html b/src/git.html new file mode 100644 index 0000000..987ec9e --- /dev/null +++ b/src/git.html @@ -0,0 +1,19 @@ +<html> + <head> + <meta http-equiv="Content-Type" content="text/html; charset=Unicode" /> + <style text="text/css"> + body + { + margin: 0; + width: 1100px; + height: 850px; + } + </style> + </head> + + <body> + <div id="gadgetContent"> + <img src="git-cheat-sheet-medium.png" /> + </div> + </body> +</html> \ No newline at end of file
Tigraine/git-cheatsheet-gadget
b6960ffb0213cb30f58897dbed8b2d4b12791206
Added gadget.xml and git-logo
diff --git a/src/gadget.xml b/src/gadget.xml new file mode 100644 index 0000000..8032f9b --- /dev/null +++ b/src/gadget.xml @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="utf-8" ?> +<gadget> + <name>git-cheatsheet</name> + <namespace>windows.sdk</namespace> + <version>1.0.0.0</version> + <author name="Daniel Hölbling"> + <info url="http://www.tigraine.at" /> + <logo src="git-logo.png" /> + </author> + <copyright>&#169; Daniel Hölbling.</copyright> + <description>Displays a GIT cheatsheet on the Desktop.</description> + <icons> + <icon height="48" width="48" src="icon.png" /> + </icons> + <hosts> + <host name="sidebar"> + <base type="HTML" apiVersion="1.0.0" src="sidebar.html" /> + <permissions>Full</permissions> + <platform minPlatformVersion="1.0" /> + <defaultImage src="git-logo.png" /> + </host> + </hosts> +</gadget> \ No newline at end of file diff --git a/src/git-logo.png b/src/git-logo.png new file mode 100644 index 0000000..ac22ccb Binary files /dev/null and b/src/git-logo.png differ
jeffp/why_not
e91aaf825381c27d203136415025bf7b26e49d46
incremented gem version
diff --git a/next_gem_version b/next_gem_version index 81340c7..bbdeab6 100644 --- a/next_gem_version +++ b/next_gem_version @@ -1 +1 @@ -0.0.4 +0.0.5
jeffp/why_not
8ae2077306af91c2d16f27555d999c9e90354cc3
adds isnt and is_not
diff --git a/README.rdoc b/README.rdoc index 5d9c672..f426a95 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,32 +1,35 @@ = WhyNot? not_empty?, not_blank?, ... why_not? Tired of writing !array.empty? Ruby is ledgible and should be more ledgible. Ruby is terse and should be terser. A predicate method is one that returns a boolean and ends in a question mark. This simple library adds corresponding negation methods for all Ruby predicate methods. == Resources Install * sudo gem install why_not Use * require 'why_not' == Usage In general array = %w(one two three) array.empty? # => false array.not_empty? # => true value = nil value.nil? # => true value.not_nil? # => false + [].is_not_a?(Array) # => false + [].isnt_a?(String) # => true + == Dependencies * rubygems * meta_programming diff --git a/Rakefile b/Rakefile index 4482e46..e007bf6 100644 --- a/Rakefile +++ b/Rakefile @@ -1,72 +1,67 @@ #require 'rake/testtask' require 'rake/rdoctask' require 'rake/gempackagetask' gem 'gem_version', '>= 0.0.1' require 'gem_version' #require 'rake/contrib/sshpublisher' spec = Gem::Specification.new do |s| s.name = 'why_not' s.version = GemVersion.next_version s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 1.8.7' s.description = 'not_empty?, not_blank?, not_defined? ... why not? This is Ruby, come on.' s.summary = 'Comprehensive negation for all Ruby predicate methods.' - s.add_dependency('meta_programming', '>= 0.0.2') + s.add_dependency('meta_programming', '>= 0.0.6') exclude_folders = '' # 'spec/rails/{doc,lib,log,nbproject,tmp,vendor,test}' exclude_files = [] # FileList['**/*.log'] + FileList[exclude_folders+'/**/*'] + FileList[exclude_folders] s.files = FileList['{lib,spec}/**/*'] + %w(init.rb LICENSE Rakefile README.rdoc .gitignore) - exclude_files s.require_path = 'lib' s.has_rdoc = true s.test_files = Dir['spec/*_spec.rb'] s.author = 'Jeff Patmon' s.email = '[email protected]' s.homepage = 'http://github.com/jeffp/why_not/tree/master' end require 'spec/version' require 'spec/rake/spectask' desc "Run specs" Spec::Rake::SpecTask.new(:spec) do |t| t.spec_files = FileList['spec/*_spec.rb'] t.libs << 'lib' << 'spec' t.rcov = false t.spec_opts = ['--options', 'spec/spec.opts'] #t.rcov_dir = 'coverage' #t.rcov_opts = ['--exclude', "kernel,load-diff-lcs\.rb,instance_exec\.rb,lib/spec.rb,lib/spec/runner.rb,^spec/*,bin/spec,examples,/gems,/Library/Ruby,\.autotest,#{ENV['GEM_HOME']}"] end desc "Generate documentation for the #{spec.name} gem." Rake::RDocTask.new(:rdoc) do |rdoc| rdoc.rdoc_dir = 'rdoc' rdoc.title = spec.name #rdoc.template = '../rdoc_template.rb' rdoc.options << '--line-numbers' << '--inline-source' rdoc.rdoc_files.include('README.rdoc', 'LICENSE', 'lib/**/*.rb') end -desc 'Clean up gem build.' -task :clean do - FileUtils.rm_f Dir.glob('*.gem') -end - desc 'Generate a gemspec file.' task :gemspec do File.open("#{spec.name}.gemspec", 'w') do |f| f.write spec.to_ruby end GemVersion.increment_version GemVersion.commit_and_push end Rake::GemPackageTask.new(spec) do |p| p.gem_spec = spec p.need_tar = RUBY_PLATFORM =~ /mswin/ ? false : true p.need_zip = true end Dir['tasks/**/*.rake'].each {|rake| load rake} diff --git a/lib/why_not.rb b/lib/why_not.rb index 71abd63..abe6136 100644 --- a/lib/why_not.rb +++ b/lib/why_not.rb @@ -1,11 +1,19 @@ require 'meta_programming' class Object define_ghost_method(/^not_.+\?$/) do |object, symbol, *args| symbol.to_s =~ /^not_(.+\?)$/ regular_method = $1.to_sym !object.__send__(regular_method, *args) end + define_ghost_method(/^is(nt|_not)_.+\?$/) do |object, symbol, *args| + (method = symbol.to_s) =~ /^is(nt|_not)_/ + regular_method = case $1 + when 'nt' then method.gsub(/^isnt_/, 'is_').to_sym + when '_not' then method.gsub(/^is_not_/, 'is_').to_sym + end + !object.__send__(regular_method, *args) + end end diff --git a/spec/why_not_spec.rb b/spec/why_not_spec.rb index 2c4258e..10b82eb 100644 --- a/spec/why_not_spec.rb +++ b/spec/why_not_spec.rb @@ -1,50 +1,66 @@ require 'spec_helper' require 'lib/why_not' describe "WhyNot" do + describe "/^is(nt|_not)_.+\?$/ method" do + it "should work for isnt_a? method" do + [].isnt_a?(Array).should be_false + [].isnt_a?(String).should be_true + end + it "should work for is_not_a? method" do + [].is_not_a?(Array).should be_false + [].is_not_a?(String).should be_true + end + it "should raise error for is_not_azzz?" do + lambda { [].is_not_azzz?(Array) }.should raise_exception(NoMethodError) + end + it "should raise error for isnt_azzz?" do + lambda { [].isnt_azzz?(Array) }.should raise_exception(NoMethodError) + end + end describe "/^not_.*\?$/ method" do it "should work for empty? method on arrays" do array = [] array.empty?.should be_true lambda { array.not_empty?.should be_false }.should_not raise_exception array = %w(one two three four five) array.empty?.should be_false array.not_empty?.should be_true end it "should work for NilClass" do obj = nil obj.nil?.should be_true lambda { obj.not_nil?.should be_false }.should_not raise_exception end it "should raise NoMethodError if associated method does not exist" do array = %w(one two three) lambda { array.not_even? }.should raise_exception(NoMethodError, /even/) end it "should work for methods defined through opening a class" do class TestArray < Array; def even?; self.size%2 == 0; end; end array = TestArray.new(%w(one two three)) lambda { array.even?.should == false }.should_not raise_exception lambda { array.not_even?.should == true}.should_not raise_exception end it "should raise NoMethodError when not negating a test (?) method" do array = %w(one two three) lambda { array.not_length }.should raise_exception(NoMethodError, /not_length/) end it "should not access protected methods but should from inside method call" do class TestArray < Array; def protected_odd?; self.size % 2 != 0; end; protected :protected_odd?; end array = TestArray.new(%w(one two three)) lambda { array.protected_odd? }.should raise_exception class TestArray < Array; def inner_odd?; protected_odd?; end; end lambda { array.inner_odd?.should == true }.should_not raise_exception lambda { array.not_inner_odd?.should == false}.should_not raise_exception end it "should not access private methods but should from inside method call" do class TestArray < Array; def private_odd?; self.size % 2 != 0; end; private :private_odd?; end array = TestArray.new(%w(one two three)) lambda { array.privat_odd? }.should raise_exception class TestArray < Array; def inner_odd?; private_odd?; end; end lambda { array.inner_odd?.should == true }.should_not raise_exception lambda { array.not_inner_odd?.should == false}.should_not raise_exception end end end
jeffp/why_not
1a19aa39e6dc9e2a369db5363a33a4de6db22d4c
incremented gem version
diff --git a/next_gem_version b/next_gem_version index bcab45a..81340c7 100644 --- a/next_gem_version +++ b/next_gem_version @@ -1 +1 @@ -0.0.3 +0.0.4
jeffp/why_not
0dd8cbe7e9412def55e0f58d3986488107956379
incremented gem version
diff --git a/next_gem_version b/next_gem_version index 4e379d2..bcab45a 100644 --- a/next_gem_version +++ b/next_gem_version @@ -1 +1 @@ -0.0.2 +0.0.3
jeffp/why_not
2de580c2fce259da38d15036e710b9e8f6221f43
incremented gem version
diff --git a/next_gem_version b/next_gem_version index 8acdd82..4e379d2 100644 --- a/next_gem_version +++ b/next_gem_version @@ -1 +1 @@ -0.0.1 +0.0.2
mmitch/s9y_poster_import
dddbec6e45a509e5ef570a94ec5f0c406ac46b28
support multiple authors
diff --git a/s9y_poster_import.pl b/s9y_poster_import.pl index 922dea1..2f19ffe 100755 --- a/s9y_poster_import.pl +++ b/s9y_poster_import.pl @@ -1,259 +1,282 @@ #!/usr/bin/perl # $Id: s9y_poster_import.pl,v 1.6 2007-10-06 12:17:23 mitch Exp $ use strict; use warnings; use Time::Local; use Data::Dumper; use DBI; # this script imports a poster blog ( ) into Serendipity (www.s9y.org) # it has been tested with poster 1.0.8 and s9y # # 2007 (c) by Christian Garbs <[email protected]> # licensed under GNU GPL v2 # # USAGE: # # 1. edit below to set up the database connection and your S9Y table prefix # 2. run this script with the poster data directory as first argument my $dbh = DBI->connect( 'DBI:mysql:database=serendipity;host=localhost;port=3306', 'serendipity', # username 'ihego906', # password {'PrintError' => 1, 'PrintWarn' => 1, 'ShowErrorStatement' => 1, }, # {'RaiseError' => 1} ); my $tableprefix = 'serendipity_'; # use utf8? $dbh->do('SET NAMES utf8'); ################################################################################################### # process arguments my $posterdir = $ARGV[0]; die "needs poster data directory as first argument" unless defined $posterdir and $posterdir ne ''; # global variables my %mapping; # read categories my %category; open CATEGORY, '<', "$posterdir/../categories" or die "can't open `$posterdir/../categories': $1"; while (my $line = <CATEGORY>) { my ($short, $name, undef) = split /:/, $line, 3; $category{$short} = $name; } close CATEGORY or die "can't open `$posterdir/../categories': $1"; +# read and process users +my %user; +open USER, '<', "$posterdir/../users" or die "can't open `$posterdir/../users': $1"; +while (my $line = <USER>) { + my ($user, $pwdhash, $name, $url, $date) = split /(?<!\\):/, $line, 5; + + my $insert_entry = + sprintf('INSERT INTO %sauthors (realname, username, password ) VALUES ( %s, %s, %s )', + $tableprefix, + $dbh->quote($name), + $dbh->quote($user), + $dbh->quote($pwdhash) + ); + + $dbh->do($insert_entry); + + $user{$user} = $dbh->last_insert_id(undef, undef, undef, undef); + + print "user $user imported as #$user{$user}.\n"; +} +close USER or die "can't open `$posterdir/../users': $1"; + # read entries opendir ENTRY, $posterdir or die "can't opendir `$posterdir': $!"; my @entry = sort grep { -d "$posterdir/$_" and $_ =~ /^\d{14}$/ } readdir(ENTRY); closedir ENTRY or die "can't closedir `$posterdir': $!"; print @entry . " entries found.\n"; # process entries foreach my $entry (@entry) { print "entry $entry...\n"; my $dir = "$posterdir/$entry"; my $line; my %entry; # read comments opendir COMMENT, "$dir/comments/" or die "can't opendir `$dir/comments/': $!"; my @comment = sort grep { -f "$dir/comments/$_" and $_ =~ /^\d{14}$/ } readdir(COMMENT); closedir COMMENT or die "can't closedir `$dir/comments/': $!"; print " " . @comment . " comments found.\n"; # read trackbacks opendir TRACKBACK, "$dir/trackbacks/" or die "can't opendir `$dir/trackbacks/': $!"; my @trackback = sort grep { -f "$dir/trackbacks/$_" and $_ =~ /^\d{14}$/ } readdir(TRACKBACK); closedir TRACKBACK or die "can't closedir `$dir/trackbacks/': $!"; print " " . @trackback . " trackbacks found.\n"; # process entry $entry{TIMESTAMP} = timelocal( substr($entry, 12, 2), substr($entry, 10, 2), substr($entry, 8, 2), substr($entry, 6, 2), substr($entry, 4, 2)-1, substr($entry, 0, 4) ); open ENTRY, '<', "$dir/post" or die "can't open `$dir/post': $!"; ## the first three lines contain administrative data (AUTHOR, CATEGORY, TITLE) for (1..3) { $line = <ENTRY>; chomp $line; if ($line =~ /^([A-Z_]+): (.*)$/) { $entry{$1} = $2; } } while ($line = <ENTRY>) { chomp $line; $entry{BODY} .= $line .' '; } $entry{BODY} =~ s/\s+$//; close ENTRY or die "can't close `$dir/post': $!"; # process comments $entry{COMMENTS} = []; foreach my $comment (sort @comment) { my %comment; $comment{TIMESTAMP} = timelocal( substr($comment, 12, 2), substr($comment, 10, 2), substr($comment, 8, 2), substr($comment, 6, 2), substr($comment, 4, 2)-1, substr($comment, 0, 4) ); open COMMENT, '<', "$dir/comments/$comment" or die "can't open `$dir/comments/$comment': $!"; $line = <COMMENT>; chomp $line; if ($line =~ /^AUTHOR: (.*)$/) { $line = $1; if ($line =~ /^(.*?):(.*)$/) { $comment{AUTHOR} = $1; $comment{URL} = $2 unless $2 =~ m|^http\\://www.cgarbs.de/blog/index.php/|; } else { $comment{AUTHOR} = $line; } } while ($line = <COMMENT>) { chomp $line; $comment{BODY} .= $line .' '; } $comment{BODY} =~ s/\s+$//; close COMMENT or die "can't close `$dir/comments/$comment': $!"; push @{$entry{COMMENTS}}, {%comment}; } # process trackbacks $entry{TRACKBACKS} = []; foreach my $trackback (sort @trackback) { my %trackback; $trackback{TIMESTAMP} = timelocal( substr($trackback, 12, 2), substr($trackback, 10, 2), substr($trackback, 8, 2), substr($trackback, 6, 2), substr($trackback, 4, 2)-1, substr($trackback, 0, 4) ); open TRACKBACK, '<', "$dir/trackbacks/$trackback" or die "can't open `$dir/trackbacks/$trackback': $!"; ## the first three lines contain administrative data (URL, TITLE, BLOG_NAME) for (1..3) { $line = <TRACKBACK>; chomp $line; if ($line =~ /^([A-Z_]+): (.*)$/) { $trackback{$1} = $2; } } while ($line = <TRACKBACK>) { chomp $line; $trackback{BODY} .= $line .' '; } $trackback{BODY} =~ s/\s+$//; close TRACKBACK or die "can't close `$dir/trackbacks/$trackback': $!"; push @{$entry{TRACKBACKS}}, {%trackback}; } print "\n"; # save entry my $insert_entry = - sprintf('INSERT INTO %sentries (title, timestamp, body, comments, trackbacks, author, authorid ) VALUES ( %s, %d, %s, %d, %d, %s, %d )', + sprintf('INSERT INTO %sentries (title, timestamp, body, comments, trackbacks, author, authorid, isdraft ) VALUES ( %s, %d, %s, %d, %d, %s, %d, %s )', $tableprefix, $dbh->quote($entry{TITLE}), $entry{TIMESTAMP} + 0, $dbh->quote($entry{BODY}), 0, 0, $dbh->quote($entry{AUTHOR}), - 1 + $user{$entry{AUTHOR}}, + $dbh->quote('false') ); $dbh->do($insert_entry); my $entryid = $dbh->last_insert_id(undef, undef, undef, undef); $mapping{$entry} = $entryid; # save category if (exists $category{$entry{CATEGORY}}) { my $get_category = $dbh->prepare(sprintf('SELECT categoryid FROM %scategory WHERE category_name = %s', $tableprefix, $dbh->quote($category{$entry{CATEGORY}}) )); $get_category->execute(); if (my $ref = $get_category->fetchrow_hashref()) { my $insert_category = sprintf('INSERT INTO %sentrycat (entryid, categoryid) VALUES ( %d, %d )', $tableprefix, $entryid, $ref->{categoryid} + 0 ); $dbh->do($insert_category); } } # save comments foreach my $comment (@{$entry{COMMENTS}}) { my $insert_comment = sprintf('INSERT INTO %scomments (entry_id, timestamp, author, url, body, type, status) VALUES ( %d, %d, %s, %s, %s, %s, %s )', $tableprefix, $entryid, $comment->{TIMESTAMP}, $dbh->quote($comment->{AUTHOR}), exists $comment->{URL} ? $dbh->quote($comment->{URL}) : 'NULL', $dbh->quote($comment->{BODY}), $dbh->quote('NORMAL'), $dbh->quote('pending') ); $dbh->do($insert_comment); } # save trackbacks foreach my $trackback (@{$entry{TRACKBACKS}}) { my $insert_trackback = sprintf('INSERT INTO %scomments (entry_id, timestamp, author, url, body, type, status) VALUES ( %d, %d, %s, %s, %s, %s, %s )', $tableprefix, $entryid, $trackback->{TIMESTAMP}, $dbh->quote($trackback->{BLOG_NAME}), exists $trackback->{URL} ? $dbh->quote($trackback->{URL}) : 'NULL', $dbh->quote($trackback->{BODY}), $dbh->quote('TRACKBACK'), $dbh->quote('pending') ); $dbh->do($insert_trackback); } } # print mapping print "\nmapped entries:\n"; print "$_ $mapping{$_}\n" foreach (sort keys %mapping); __DATA__ # SQL to delete imports after test run # (I want to keep my entry 1, it's a real test entry that's not imported from poster) delete from serendipity_comments where entry_id != 1; delete from serendipity_entries where id != 1; delete from serendipity_entrycat where entryid != 1; delete from serendipity_references where entry_id != 1; - +delete from serendipity_authors where authorid != 1;
mmitch/s9y_poster_import
3d1a87473e6d4b98272cdd383aefa3e83bb5c404
fix documentation
diff --git a/s9y_poster_import.pl b/s9y_poster_import.pl index ea8e245..922dea1 100755 --- a/s9y_poster_import.pl +++ b/s9y_poster_import.pl @@ -1,259 +1,259 @@ #!/usr/bin/perl -# $Id: s9y_poster_import.pl,v 1.5 2007-10-03 10:01:50 mitch Exp $ +# $Id: s9y_poster_import.pl,v 1.6 2007-10-06 12:17:23 mitch Exp $ use strict; use warnings; use Time::Local; use Data::Dumper; use DBI; # this script imports a poster blog ( ) into Serendipity (www.s9y.org) -# it has been tested with poster 1.0.6 and s9y +# it has been tested with poster 1.0.8 and s9y # # 2007 (c) by Christian Garbs <[email protected]> # licensed under GNU GPL v2 # # USAGE: # # 1. edit below to set up the database connection and your S9Y table prefix # 2. run this script with the poster data directory as first argument my $dbh = DBI->connect( 'DBI:mysql:database=serendipity;host=localhost;port=3306', 'serendipity', # username 'ihego906', # password {'PrintError' => 1, 'PrintWarn' => 1, 'ShowErrorStatement' => 1, }, # {'RaiseError' => 1} ); my $tableprefix = 'serendipity_'; # use utf8? $dbh->do('SET NAMES utf8'); ################################################################################################### # process arguments my $posterdir = $ARGV[0]; die "needs poster data directory as first argument" unless defined $posterdir and $posterdir ne ''; # global variables my %mapping; # read categories my %category; open CATEGORY, '<', "$posterdir/../categories" or die "can't open `$posterdir/../categories': $1"; while (my $line = <CATEGORY>) { my ($short, $name, undef) = split /:/, $line, 3; $category{$short} = $name; } close CATEGORY or die "can't open `$posterdir/../categories': $1"; # read entries opendir ENTRY, $posterdir or die "can't opendir `$posterdir': $!"; my @entry = sort grep { -d "$posterdir/$_" and $_ =~ /^\d{14}$/ } readdir(ENTRY); closedir ENTRY or die "can't closedir `$posterdir': $!"; print @entry . " entries found.\n"; # process entries foreach my $entry (@entry) { print "entry $entry...\n"; my $dir = "$posterdir/$entry"; my $line; my %entry; # read comments opendir COMMENT, "$dir/comments/" or die "can't opendir `$dir/comments/': $!"; my @comment = sort grep { -f "$dir/comments/$_" and $_ =~ /^\d{14}$/ } readdir(COMMENT); closedir COMMENT or die "can't closedir `$dir/comments/': $!"; print " " . @comment . " comments found.\n"; # read trackbacks opendir TRACKBACK, "$dir/trackbacks/" or die "can't opendir `$dir/trackbacks/': $!"; my @trackback = sort grep { -f "$dir/trackbacks/$_" and $_ =~ /^\d{14}$/ } readdir(TRACKBACK); closedir TRACKBACK or die "can't closedir `$dir/trackbacks/': $!"; print " " . @trackback . " trackbacks found.\n"; # process entry $entry{TIMESTAMP} = timelocal( substr($entry, 12, 2), substr($entry, 10, 2), substr($entry, 8, 2), substr($entry, 6, 2), substr($entry, 4, 2)-1, substr($entry, 0, 4) ); open ENTRY, '<', "$dir/post" or die "can't open `$dir/post': $!"; ## the first three lines contain administrative data (AUTHOR, CATEGORY, TITLE) for (1..3) { $line = <ENTRY>; chomp $line; if ($line =~ /^([A-Z_]+): (.*)$/) { $entry{$1} = $2; } } while ($line = <ENTRY>) { chomp $line; $entry{BODY} .= $line .' '; } $entry{BODY} =~ s/\s+$//; close ENTRY or die "can't close `$dir/post': $!"; # process comments $entry{COMMENTS} = []; foreach my $comment (sort @comment) { my %comment; $comment{TIMESTAMP} = timelocal( substr($comment, 12, 2), substr($comment, 10, 2), substr($comment, 8, 2), substr($comment, 6, 2), substr($comment, 4, 2)-1, substr($comment, 0, 4) ); open COMMENT, '<', "$dir/comments/$comment" or die "can't open `$dir/comments/$comment': $!"; $line = <COMMENT>; chomp $line; if ($line =~ /^AUTHOR: (.*)$/) { $line = $1; if ($line =~ /^(.*?):(.*)$/) { $comment{AUTHOR} = $1; $comment{URL} = $2 unless $2 =~ m|^http\\://www.cgarbs.de/blog/index.php/|; } else { $comment{AUTHOR} = $line; } } while ($line = <COMMENT>) { chomp $line; $comment{BODY} .= $line .' '; } $comment{BODY} =~ s/\s+$//; close COMMENT or die "can't close `$dir/comments/$comment': $!"; push @{$entry{COMMENTS}}, {%comment}; } # process trackbacks $entry{TRACKBACKS} = []; foreach my $trackback (sort @trackback) { my %trackback; $trackback{TIMESTAMP} = timelocal( substr($trackback, 12, 2), substr($trackback, 10, 2), substr($trackback, 8, 2), substr($trackback, 6, 2), substr($trackback, 4, 2)-1, substr($trackback, 0, 4) ); open TRACKBACK, '<', "$dir/trackbacks/$trackback" or die "can't open `$dir/trackbacks/$trackback': $!"; ## the first three lines contain administrative data (URL, TITLE, BLOG_NAME) for (1..3) { $line = <TRACKBACK>; chomp $line; if ($line =~ /^([A-Z_]+): (.*)$/) { $trackback{$1} = $2; } } while ($line = <TRACKBACK>) { chomp $line; $trackback{BODY} .= $line .' '; } $trackback{BODY} =~ s/\s+$//; close TRACKBACK or die "can't close `$dir/trackbacks/$trackback': $!"; push @{$entry{TRACKBACKS}}, {%trackback}; } print "\n"; # save entry my $insert_entry = sprintf('INSERT INTO %sentries (title, timestamp, body, comments, trackbacks, author, authorid ) VALUES ( %s, %d, %s, %d, %d, %s, %d )', $tableprefix, $dbh->quote($entry{TITLE}), $entry{TIMESTAMP} + 0, $dbh->quote($entry{BODY}), 0, 0, $dbh->quote($entry{AUTHOR}), 1 ); $dbh->do($insert_entry); my $entryid = $dbh->last_insert_id(undef, undef, undef, undef); $mapping{$entry} = $entryid; # save category if (exists $category{$entry{CATEGORY}}) { my $get_category = $dbh->prepare(sprintf('SELECT categoryid FROM %scategory WHERE category_name = %s', $tableprefix, $dbh->quote($category{$entry{CATEGORY}}) )); $get_category->execute(); if (my $ref = $get_category->fetchrow_hashref()) { my $insert_category = sprintf('INSERT INTO %sentrycat (entryid, categoryid) VALUES ( %d, %d )', $tableprefix, $entryid, $ref->{categoryid} + 0 ); $dbh->do($insert_category); } } # save comments foreach my $comment (@{$entry{COMMENTS}}) { my $insert_comment = sprintf('INSERT INTO %scomments (entry_id, timestamp, author, url, body, type, status) VALUES ( %d, %d, %s, %s, %s, %s, %s )', $tableprefix, $entryid, $comment->{TIMESTAMP}, $dbh->quote($comment->{AUTHOR}), exists $comment->{URL} ? $dbh->quote($comment->{URL}) : 'NULL', $dbh->quote($comment->{BODY}), $dbh->quote('NORMAL'), $dbh->quote('pending') ); $dbh->do($insert_comment); } # save trackbacks foreach my $trackback (@{$entry{TRACKBACKS}}) { my $insert_trackback = sprintf('INSERT INTO %scomments (entry_id, timestamp, author, url, body, type, status) VALUES ( %d, %d, %s, %s, %s, %s, %s )', $tableprefix, $entryid, $trackback->{TIMESTAMP}, $dbh->quote($trackback->{BLOG_NAME}), exists $trackback->{URL} ? $dbh->quote($trackback->{URL}) : 'NULL', $dbh->quote($trackback->{BODY}), $dbh->quote('TRACKBACK'), $dbh->quote('pending') ); $dbh->do($insert_trackback); } } # print mapping print "\nmapped entries:\n"; print "$_ $mapping{$_}\n" foreach (sort keys %mapping); __DATA__ # SQL to delete imports after test run # (I want to keep my entry 1, it's a real test entry that's not imported from poster) delete from serendipity_comments where entry_id != 1; delete from serendipity_entries where id != 1; delete from serendipity_entrycat where entryid != 1; delete from serendipity_references where entry_id != 1;
mmitch/s9y_poster_import
e8c46e15b6970208161b1e89a35ee54a285ddee0
fix error
diff --git a/s9y_poster_import.pl b/s9y_poster_import.pl index 919a177..ea8e245 100755 --- a/s9y_poster_import.pl +++ b/s9y_poster_import.pl @@ -1,255 +1,259 @@ #!/usr/bin/perl -# $Id: s9y_poster_import.pl,v 1.4 2007-10-03 10:00:26 mitch Exp $ +# $Id: s9y_poster_import.pl,v 1.5 2007-10-03 10:01:50 mitch Exp $ use strict; use warnings; use Time::Local; use Data::Dumper; use DBI; # this script imports a poster blog ( ) into Serendipity (www.s9y.org) # it has been tested with poster 1.0.6 and s9y # # 2007 (c) by Christian Garbs <[email protected]> # licensed under GNU GPL v2 # # USAGE: # # 1. edit below to set up the database connection and your S9Y table prefix # 2. run this script with the poster data directory as first argument my $dbh = DBI->connect( 'DBI:mysql:database=serendipity;host=localhost;port=3306', 'serendipity', # username 'ihego906', # password {'PrintError' => 1, 'PrintWarn' => 1, 'ShowErrorStatement' => 1, }, # {'RaiseError' => 1} ); my $tableprefix = 'serendipity_'; # use utf8? $dbh->do('SET NAMES utf8'); ################################################################################################### # process arguments my $posterdir = $ARGV[0]; die "needs poster data directory as first argument" unless defined $posterdir and $posterdir ne ''; # global variables my %mapping; # read categories my %category; open CATEGORY, '<', "$posterdir/../categories" or die "can't open `$posterdir/../categories': $1"; while (my $line = <CATEGORY>) { my ($short, $name, undef) = split /:/, $line, 3; $category{$short} = $name; } close CATEGORY or die "can't open `$posterdir/../categories': $1"; # read entries opendir ENTRY, $posterdir or die "can't opendir `$posterdir': $!"; my @entry = sort grep { -d "$posterdir/$_" and $_ =~ /^\d{14}$/ } readdir(ENTRY); closedir ENTRY or die "can't closedir `$posterdir': $!"; print @entry . " entries found.\n"; # process entries foreach my $entry (@entry) { print "entry $entry...\n"; my $dir = "$posterdir/$entry"; my $line; my %entry; # read comments opendir COMMENT, "$dir/comments/" or die "can't opendir `$dir/comments/': $!"; my @comment = sort grep { -f "$dir/comments/$_" and $_ =~ /^\d{14}$/ } readdir(COMMENT); closedir COMMENT or die "can't closedir `$dir/comments/': $!"; print " " . @comment . " comments found.\n"; # read trackbacks opendir TRACKBACK, "$dir/trackbacks/" or die "can't opendir `$dir/trackbacks/': $!"; my @trackback = sort grep { -f "$dir/trackbacks/$_" and $_ =~ /^\d{14}$/ } readdir(TRACKBACK); closedir TRACKBACK or die "can't closedir `$dir/trackbacks/': $!"; print " " . @trackback . " trackbacks found.\n"; # process entry $entry{TIMESTAMP} = timelocal( substr($entry, 12, 2), substr($entry, 10, 2), substr($entry, 8, 2), substr($entry, 6, 2), substr($entry, 4, 2)-1, substr($entry, 0, 4) ); open ENTRY, '<', "$dir/post" or die "can't open `$dir/post': $!"; ## the first three lines contain administrative data (AUTHOR, CATEGORY, TITLE) for (1..3) { $line = <ENTRY>; chomp $line; if ($line =~ /^([A-Z_]+): (.*)$/) { $entry{$1} = $2; } } while ($line = <ENTRY>) { chomp $line; $entry{BODY} .= $line .' '; } $entry{BODY} =~ s/\s+$//; close ENTRY or die "can't close `$dir/post': $!"; # process comments $entry{COMMENTS} = []; foreach my $comment (sort @comment) { my %comment; $comment{TIMESTAMP} = timelocal( substr($comment, 12, 2), substr($comment, 10, 2), substr($comment, 8, 2), substr($comment, 6, 2), substr($comment, 4, 2)-1, substr($comment, 0, 4) ); open COMMENT, '<', "$dir/comments/$comment" or die "can't open `$dir/comments/$comment': $!"; $line = <COMMENT>; chomp $line; if ($line =~ /^AUTHOR: (.*)$/) { $line = $1; if ($line =~ /^(.*?):(.*)$/) { $comment{AUTHOR} = $1; $comment{URL} = $2 unless $2 =~ m|^http\\://www.cgarbs.de/blog/index.php/|; } else { $comment{AUTHOR} = $line; } } while ($line = <COMMENT>) { chomp $line; $comment{BODY} .= $line .' '; } $comment{BODY} =~ s/\s+$//; close COMMENT or die "can't close `$dir/comments/$comment': $!"; push @{$entry{COMMENTS}}, {%comment}; } # process trackbacks $entry{TRACKBACKS} = []; foreach my $trackback (sort @trackback) { my %trackback; $trackback{TIMESTAMP} = timelocal( substr($trackback, 12, 2), substr($trackback, 10, 2), substr($trackback, 8, 2), substr($trackback, 6, 2), substr($trackback, 4, 2)-1, substr($trackback, 0, 4) ); open TRACKBACK, '<', "$dir/trackbacks/$trackback" or die "can't open `$dir/trackbacks/$trackback': $!"; ## the first three lines contain administrative data (URL, TITLE, BLOG_NAME) for (1..3) { $line = <TRACKBACK>; chomp $line; if ($line =~ /^([A-Z_]+): (.*)$/) { $trackback{$1} = $2; } } while ($line = <TRACKBACK>) { chomp $line; $trackback{BODY} .= $line .' '; } $trackback{BODY} =~ s/\s+$//; close TRACKBACK or die "can't close `$dir/trackbacks/$trackback': $!"; push @{$entry{TRACKBACKS}}, {%trackback}; } print "\n"; # save entry my $insert_entry = sprintf('INSERT INTO %sentries (title, timestamp, body, comments, trackbacks, author, authorid ) VALUES ( %s, %d, %s, %d, %d, %s, %d )', $tableprefix, $dbh->quote($entry{TITLE}), $entry{TIMESTAMP} + 0, $dbh->quote($entry{BODY}), 0, 0, $dbh->quote($entry{AUTHOR}), 1 ); $dbh->do($insert_entry); my $entryid = $dbh->last_insert_id(undef, undef, undef, undef); $mapping{$entry} = $entryid; # save category if (exists $category{$entry{CATEGORY}}) { my $get_category = $dbh->prepare(sprintf('SELECT categoryid FROM %scategory WHERE category_name = %s', $tableprefix, $dbh->quote($category{$entry{CATEGORY}}) )); $get_category->execute(); if (my $ref = $get_category->fetchrow_hashref()) { my $insert_category = - sprintf('INSERT INTO %sentrycat (entryid, categoryid) VALUES ( %d, %d )', $entryid, $ref->{categoryid} + 0); + sprintf('INSERT INTO %sentrycat (entryid, categoryid) VALUES ( %d, %d )', + $tableprefix, + $entryid, + $ref->{categoryid} + 0 + ); $dbh->do($insert_category); } } # save comments foreach my $comment (@{$entry{COMMENTS}}) { my $insert_comment = sprintf('INSERT INTO %scomments (entry_id, timestamp, author, url, body, type, status) VALUES ( %d, %d, %s, %s, %s, %s, %s )', $tableprefix, $entryid, $comment->{TIMESTAMP}, $dbh->quote($comment->{AUTHOR}), exists $comment->{URL} ? $dbh->quote($comment->{URL}) : 'NULL', $dbh->quote($comment->{BODY}), $dbh->quote('NORMAL'), $dbh->quote('pending') ); $dbh->do($insert_comment); } # save trackbacks foreach my $trackback (@{$entry{TRACKBACKS}}) { my $insert_trackback = sprintf('INSERT INTO %scomments (entry_id, timestamp, author, url, body, type, status) VALUES ( %d, %d, %s, %s, %s, %s, %s )', $tableprefix, $entryid, $trackback->{TIMESTAMP}, $dbh->quote($trackback->{BLOG_NAME}), exists $trackback->{URL} ? $dbh->quote($trackback->{URL}) : 'NULL', $dbh->quote($trackback->{BODY}), $dbh->quote('TRACKBACK'), $dbh->quote('pending') ); $dbh->do($insert_trackback); } } # print mapping print "\nmapped entries:\n"; print "$_ $mapping{$_}\n" foreach (sort keys %mapping); __DATA__ # SQL to delete imports after test run # (I want to keep my entry 1, it's a real test entry that's not imported from poster) delete from serendipity_comments where entry_id != 1; delete from serendipity_entries where id != 1; delete from serendipity_entrycat where entryid != 1; delete from serendipity_references where entry_id != 1;
mmitch/s9y_poster_import
477ea3d8998b9585f544297cc6a51b7aa7f2edfb
remove debug print mapping
diff --git a/s9y_poster_import.pl b/s9y_poster_import.pl index e33fd1f..919a177 100755 --- a/s9y_poster_import.pl +++ b/s9y_poster_import.pl @@ -1,259 +1,255 @@ #!/usr/bin/perl -# $Id: s9y_poster_import.pl,v 1.3 2007-10-03 09:56:17 mitch Exp $ +# $Id: s9y_poster_import.pl,v 1.4 2007-10-03 10:00:26 mitch Exp $ use strict; use warnings; use Time::Local; use Data::Dumper; use DBI; # this script imports a poster blog ( ) into Serendipity (www.s9y.org) # it has been tested with poster 1.0.6 and s9y # # 2007 (c) by Christian Garbs <[email protected]> # licensed under GNU GPL v2 # # USAGE: # # 1. edit below to set up the database connection and your S9Y table prefix # 2. run this script with the poster data directory as first argument my $dbh = DBI->connect( 'DBI:mysql:database=serendipity;host=localhost;port=3306', 'serendipity', # username 'ihego906', # password {'PrintError' => 1, 'PrintWarn' => 1, 'ShowErrorStatement' => 1, }, # {'RaiseError' => 1} ); my $tableprefix = 'serendipity_'; +# use utf8? +$dbh->do('SET NAMES utf8'); + ################################################################################################### +# process arguments my $posterdir = $ARGV[0]; - die "needs poster data directory as first argument" unless defined $posterdir and $posterdir ne ''; -# use utf8 -$dbh->do('SET NAMES utf8'); +# global variables +my %mapping; # read categories my %category; open CATEGORY, '<', "$posterdir/../categories" or die "can't open `$posterdir/../categories': $1"; while (my $line = <CATEGORY>) { my ($short, $name, undef) = split /:/, $line, 3; $category{$short} = $name; } close CATEGORY or die "can't open `$posterdir/../categories': $1"; # read entries opendir ENTRY, $posterdir or die "can't opendir `$posterdir': $!"; my @entry = sort grep { -d "$posterdir/$_" and $_ =~ /^\d{14}$/ } readdir(ENTRY); closedir ENTRY or die "can't closedir `$posterdir': $!"; print @entry . " entries found.\n"; # process entries foreach my $entry (@entry) { print "entry $entry...\n"; - + my $dir = "$posterdir/$entry"; my $line; my %entry; - + # read comments opendir COMMENT, "$dir/comments/" or die "can't opendir `$dir/comments/': $!"; my @comment = sort grep { -f "$dir/comments/$_" and $_ =~ /^\d{14}$/ } readdir(COMMENT); closedir COMMENT or die "can't closedir `$dir/comments/': $!"; print " " . @comment . " comments found.\n"; # read trackbacks opendir TRACKBACK, "$dir/trackbacks/" or die "can't opendir `$dir/trackbacks/': $!"; my @trackback = sort grep { -f "$dir/trackbacks/$_" and $_ =~ /^\d{14}$/ } readdir(TRACKBACK); closedir TRACKBACK or die "can't closedir `$dir/trackbacks/': $!"; print " " . @trackback . " trackbacks found.\n"; # process entry - ## TODO: localtime or gmtime?? $entry{TIMESTAMP} = timelocal( substr($entry, 12, 2), substr($entry, 10, 2), substr($entry, 8, 2), substr($entry, 6, 2), substr($entry, 4, 2)-1, substr($entry, 0, 4) ); open ENTRY, '<', "$dir/post" or die "can't open `$dir/post': $!"; ## the first three lines contain administrative data (AUTHOR, CATEGORY, TITLE) for (1..3) { $line = <ENTRY>; chomp $line; if ($line =~ /^([A-Z_]+): (.*)$/) { $entry{$1} = $2; } } while ($line = <ENTRY>) { chomp $line; $entry{BODY} .= $line .' '; } $entry{BODY} =~ s/\s+$//; close ENTRY or die "can't close `$dir/post': $!"; # process comments $entry{COMMENTS} = []; foreach my $comment (sort @comment) { my %comment; - ## TODO: localtime or gmtime?? $comment{TIMESTAMP} = timelocal( substr($comment, 12, 2), substr($comment, 10, 2), substr($comment, 8, 2), substr($comment, 6, 2), substr($comment, 4, 2)-1, substr($comment, 0, 4) ); open COMMENT, '<', "$dir/comments/$comment" or die "can't open `$dir/comments/$comment': $!"; $line = <COMMENT>; chomp $line; if ($line =~ /^AUTHOR: (.*)$/) { $line = $1; if ($line =~ /^(.*?):(.*)$/) { $comment{AUTHOR} = $1; $comment{URL} = $2 unless $2 =~ m|^http\\://www.cgarbs.de/blog/index.php/|; } else { $comment{AUTHOR} = $line; } } while ($line = <COMMENT>) { chomp $line; $comment{BODY} .= $line .' '; } $comment{BODY} =~ s/\s+$//; close COMMENT or die "can't close `$dir/comments/$comment': $!"; push @{$entry{COMMENTS}}, {%comment}; } # process trackbacks $entry{TRACKBACKS} = []; foreach my $trackback (sort @trackback) { my %trackback; - ## TODO: localtime or gmtime?? $trackback{TIMESTAMP} = timelocal( substr($trackback, 12, 2), substr($trackback, 10, 2), substr($trackback, 8, 2), substr($trackback, 6, 2), substr($trackback, 4, 2)-1, substr($trackback, 0, 4) ); open TRACKBACK, '<', "$dir/trackbacks/$trackback" or die "can't open `$dir/trackbacks/$trackback': $!"; ## the first three lines contain administrative data (URL, TITLE, BLOG_NAME) for (1..3) { $line = <TRACKBACK>; chomp $line; if ($line =~ /^([A-Z_]+): (.*)$/) { $trackback{$1} = $2; } } while ($line = <TRACKBACK>) { chomp $line; $trackback{BODY} .= $line .' '; } $trackback{BODY} =~ s/\s+$//; close TRACKBACK or die "can't close `$dir/trackbacks/$trackback': $!"; push @{$entry{TRACKBACKS}}, {%trackback}; } - + print "\n"; - - -## next unless @{$entry{TRACKBACKS}} > 0 and @{$entry{COMMENTS}} > 0; - + # save entry my $insert_entry = sprintf('INSERT INTO %sentries (title, timestamp, body, comments, trackbacks, author, authorid ) VALUES ( %s, %d, %s, %d, %d, %s, %d )', $tableprefix, $dbh->quote($entry{TITLE}), $entry{TIMESTAMP} + 0, $dbh->quote($entry{BODY}), 0, 0, $dbh->quote($entry{AUTHOR}), 1 ); - -# print "$insert_entry\n"; + $dbh->do($insert_entry); - + my $entryid = $dbh->last_insert_id(undef, undef, undef, undef); - + $mapping{$entry} = $entryid; + # save category if (exists $category{$entry{CATEGORY}}) { my $get_category = $dbh->prepare(sprintf('SELECT categoryid FROM %scategory WHERE category_name = %s', $tableprefix, $dbh->quote($category{$entry{CATEGORY}}) - ); + )); $get_category->execute(); if (my $ref = $get_category->fetchrow_hashref()) { my $insert_category = sprintf('INSERT INTO %sentrycat (entryid, categoryid) VALUES ( %d, %d )', $entryid, $ref->{categoryid} + 0); - # print "$insert_category\n"; $dbh->do($insert_category); } } - + # save comments foreach my $comment (@{$entry{COMMENTS}}) { my $insert_comment = sprintf('INSERT INTO %scomments (entry_id, timestamp, author, url, body, type, status) VALUES ( %d, %d, %s, %s, %s, %s, %s )', $tableprefix, $entryid, $comment->{TIMESTAMP}, $dbh->quote($comment->{AUTHOR}), exists $comment->{URL} ? $dbh->quote($comment->{URL}) : 'NULL', $dbh->quote($comment->{BODY}), $dbh->quote('NORMAL'), $dbh->quote('pending') ); - # print "$insert_comment\n"; $dbh->do($insert_comment); } # save trackbacks foreach my $trackback (@{$entry{TRACKBACKS}}) { my $insert_trackback = sprintf('INSERT INTO %scomments (entry_id, timestamp, author, url, body, type, status) VALUES ( %d, %d, %s, %s, %s, %s, %s )', $tableprefix, $entryid, $trackback->{TIMESTAMP}, $dbh->quote($trackback->{BLOG_NAME}), exists $trackback->{URL} ? $dbh->quote($trackback->{URL}) : 'NULL', $dbh->quote($trackback->{BODY}), $dbh->quote('TRACKBACK'), $dbh->quote('pending') ); - # print "$insert_trackback\n"; $dbh->do($insert_trackback); } - -## exit; - + } + +# print mapping +print "\nmapped entries:\n"; +print "$_ $mapping{$_}\n" foreach (sort keys %mapping); __DATA__ # SQL to delete imports after test run # (I want to keep my entry 1, it's a real test entry that's not imported from poster) delete from serendipity_comments where entry_id != 1; delete from serendipity_entries where id != 1; delete from serendipity_entrycat where entryid != 1; delete from serendipity_references where entry_id != 1;
mmitch/s9y_poster_import
8206da7f275569fddf330a5c72fe20b40c78db28
documentation dynamic table prefix
diff --git a/s9y_poster_import.pl b/s9y_poster_import.pl index f8a0e06..e33fd1f 100755 --- a/s9y_poster_import.pl +++ b/s9y_poster_import.pl @@ -1,237 +1,259 @@ #!/usr/bin/perl -# $Id: s9y_poster_import.pl,v 1.2 2007-09-30 16:44:03 mitch Exp $ +# $Id: s9y_poster_import.pl,v 1.3 2007-10-03 09:56:17 mitch Exp $ use strict; use warnings; use Time::Local; use Data::Dumper; use DBI; -my $posterdir = $ARGV[0]; - -die "needs poster data directory as first argument" unless defined $posterdir and $posterdir ne ''; +# this script imports a poster blog ( ) into Serendipity (www.s9y.org) +# it has been tested with poster 1.0.6 and s9y +# +# 2007 (c) by Christian Garbs <[email protected]> +# licensed under GNU GPL v2 +# +# USAGE: +# +# 1. edit below to set up the database connection and your S9Y table prefix +# 2. run this script with the poster data directory as first argument -# get database connection my $dbh = DBI->connect( 'DBI:mysql:database=serendipity;host=localhost;port=3306', - 'serendipity', - 'ihego906', + 'serendipity', # username + 'ihego906', # password {'PrintError' => 1, 'PrintWarn' => 1, 'ShowErrorStatement' => 1, - }, # {'RaiseError' => 1} ); +my $tableprefix = 'serendipity_'; + +################################################################################################### + +my $posterdir = $ARGV[0]; + +die "needs poster data directory as first argument" unless defined $posterdir and $posterdir ne ''; + # use utf8 $dbh->do('SET NAMES utf8'); # read categories my %category; open CATEGORY, '<', "$posterdir/../categories" or die "can't open `$posterdir/../categories': $1"; while (my $line = <CATEGORY>) { my ($short, $name, undef) = split /:/, $line, 3; $category{$short} = $name; } close CATEGORY or die "can't open `$posterdir/../categories': $1"; # read entries opendir ENTRY, $posterdir or die "can't opendir `$posterdir': $!"; my @entry = sort grep { -d "$posterdir/$_" and $_ =~ /^\d{14}$/ } readdir(ENTRY); closedir ENTRY or die "can't closedir `$posterdir': $!"; print @entry . " entries found.\n"; # process entries foreach my $entry (@entry) { print "entry $entry...\n"; my $dir = "$posterdir/$entry"; my $line; my %entry; # read comments opendir COMMENT, "$dir/comments/" or die "can't opendir `$dir/comments/': $!"; my @comment = sort grep { -f "$dir/comments/$_" and $_ =~ /^\d{14}$/ } readdir(COMMENT); closedir COMMENT or die "can't closedir `$dir/comments/': $!"; print " " . @comment . " comments found.\n"; # read trackbacks opendir TRACKBACK, "$dir/trackbacks/" or die "can't opendir `$dir/trackbacks/': $!"; my @trackback = sort grep { -f "$dir/trackbacks/$_" and $_ =~ /^\d{14}$/ } readdir(TRACKBACK); closedir TRACKBACK or die "can't closedir `$dir/trackbacks/': $!"; print " " . @trackback . " trackbacks found.\n"; # process entry ## TODO: localtime or gmtime?? $entry{TIMESTAMP} = timelocal( substr($entry, 12, 2), substr($entry, 10, 2), substr($entry, 8, 2), substr($entry, 6, 2), substr($entry, 4, 2)-1, substr($entry, 0, 4) ); open ENTRY, '<', "$dir/post" or die "can't open `$dir/post': $!"; ## the first three lines contain administrative data (AUTHOR, CATEGORY, TITLE) for (1..3) { $line = <ENTRY>; chomp $line; if ($line =~ /^([A-Z_]+): (.*)$/) { $entry{$1} = $2; } } while ($line = <ENTRY>) { chomp $line; $entry{BODY} .= $line .' '; } $entry{BODY} =~ s/\s+$//; close ENTRY or die "can't close `$dir/post': $!"; # process comments $entry{COMMENTS} = []; foreach my $comment (sort @comment) { my %comment; ## TODO: localtime or gmtime?? $comment{TIMESTAMP} = timelocal( substr($comment, 12, 2), substr($comment, 10, 2), substr($comment, 8, 2), substr($comment, 6, 2), substr($comment, 4, 2)-1, substr($comment, 0, 4) ); open COMMENT, '<', "$dir/comments/$comment" or die "can't open `$dir/comments/$comment': $!"; $line = <COMMENT>; chomp $line; if ($line =~ /^AUTHOR: (.*)$/) { $line = $1; if ($line =~ /^(.*?):(.*)$/) { $comment{AUTHOR} = $1; $comment{URL} = $2 unless $2 =~ m|^http\\://www.cgarbs.de/blog/index.php/|; } else { $comment{AUTHOR} = $line; } } while ($line = <COMMENT>) { chomp $line; $comment{BODY} .= $line .' '; } $comment{BODY} =~ s/\s+$//; close COMMENT or die "can't close `$dir/comments/$comment': $!"; push @{$entry{COMMENTS}}, {%comment}; } # process trackbacks $entry{TRACKBACKS} = []; foreach my $trackback (sort @trackback) { my %trackback; ## TODO: localtime or gmtime?? $trackback{TIMESTAMP} = timelocal( substr($trackback, 12, 2), substr($trackback, 10, 2), substr($trackback, 8, 2), substr($trackback, 6, 2), substr($trackback, 4, 2)-1, substr($trackback, 0, 4) ); open TRACKBACK, '<', "$dir/trackbacks/$trackback" or die "can't open `$dir/trackbacks/$trackback': $!"; ## the first three lines contain administrative data (URL, TITLE, BLOG_NAME) for (1..3) { $line = <TRACKBACK>; chomp $line; if ($line =~ /^([A-Z_]+): (.*)$/) { $trackback{$1} = $2; } } while ($line = <TRACKBACK>) { chomp $line; $trackback{BODY} .= $line .' '; } $trackback{BODY} =~ s/\s+$//; close TRACKBACK or die "can't close `$dir/trackbacks/$trackback': $!"; push @{$entry{TRACKBACKS}}, {%trackback}; } print "\n"; ## next unless @{$entry{TRACKBACKS}} > 0 and @{$entry{COMMENTS}} > 0; # save entry my $insert_entry = - sprintf('INSERT INTO serendipity_entries (title, timestamp, body, comments, trackbacks, author, authorid ) VALUES ( %s, %d, %s, %d, %d, %s, %d )', + sprintf('INSERT INTO %sentries (title, timestamp, body, comments, trackbacks, author, authorid ) VALUES ( %s, %d, %s, %d, %d, %s, %d )', + $tableprefix, $dbh->quote($entry{TITLE}), $entry{TIMESTAMP} + 0, $dbh->quote($entry{BODY}), 0, 0, $dbh->quote($entry{AUTHOR}), - 1); + 1 + ); # print "$insert_entry\n"; $dbh->do($insert_entry); my $entryid = $dbh->last_insert_id(undef, undef, undef, undef); # save category if (exists $category{$entry{CATEGORY}}) { my $get_category = - $dbh->prepare('SELECT categoryid FROM serendipity_category WHERE category_name = '.$dbh->quote($category{$entry{CATEGORY}})); + $dbh->prepare(sprintf('SELECT categoryid FROM %scategory WHERE category_name = %s', + $tableprefix, + $dbh->quote($category{$entry{CATEGORY}}) + ); $get_category->execute(); if (my $ref = $get_category->fetchrow_hashref()) { my $insert_category = - sprintf('INSERT INTO serendipity_entrycat (entryid, categoryid) VALUES ( %d, %d )', $entryid, $ref->{categoryid} + 0); + sprintf('INSERT INTO %sentrycat (entryid, categoryid) VALUES ( %d, %d )', $entryid, $ref->{categoryid} + 0); # print "$insert_category\n"; $dbh->do($insert_category); } } # save comments foreach my $comment (@{$entry{COMMENTS}}) { my $insert_comment = - sprintf('INSERT INTO serendipity_comments (entry_id, timestamp, author, url, body, type, status) VALUES ( %d, %d, %s, %s, %s, %s, %s )', + sprintf('INSERT INTO %scomments (entry_id, timestamp, author, url, body, type, status) VALUES ( %d, %d, %s, %s, %s, %s, %s )', + $tableprefix, $entryid, $comment->{TIMESTAMP}, $dbh->quote($comment->{AUTHOR}), exists $comment->{URL} ? $dbh->quote($comment->{URL}) : 'NULL', $dbh->quote($comment->{BODY}), $dbh->quote('NORMAL'), - $dbh->quote('pending')); + $dbh->quote('pending') + ); # print "$insert_comment\n"; $dbh->do($insert_comment); } # save trackbacks foreach my $trackback (@{$entry{TRACKBACKS}}) { my $insert_trackback = - sprintf('INSERT INTO serendipity_comments (entry_id, timestamp, author, url, body, type, status) VALUES ( %d, %d, %s, %s, %s, %s, %s )', - $entryid, + sprintf('INSERT INTO %scomments (entry_id, timestamp, author, url, body, type, status) VALUES ( %d, %d, %s, %s, %s, %s, %s )', + $tableprefix, + $entryid, $trackback->{TIMESTAMP}, $dbh->quote($trackback->{BLOG_NAME}), exists $trackback->{URL} ? $dbh->quote($trackback->{URL}) : 'NULL', $dbh->quote($trackback->{BODY}), $dbh->quote('TRACKBACK'), - $dbh->quote('pending')); + $dbh->quote('pending') + ); # print "$insert_trackback\n"; $dbh->do($insert_trackback); } ## exit; } __DATA__ -# restore after test run - +# SQL to delete imports after test run +# (I want to keep my entry 1, it's a real test entry that's not imported from poster) delete from serendipity_comments where entry_id != 1; delete from serendipity_entries where id != 1; delete from serendipity_entrycat where entryid != 1; delete from serendipity_references where entry_id != 1;
mmitch/s9y_poster_import
4ae52642a0a536296316b320e72f9f6aac08de55
time seems to be localtime
diff --git a/s9y_poster_import.pl b/s9y_poster_import.pl index 9280c76..f8a0e06 100755 --- a/s9y_poster_import.pl +++ b/s9y_poster_import.pl @@ -1,237 +1,237 @@ #!/usr/bin/perl -# $Id: s9y_poster_import.pl,v 1.1 2007-09-30 16:36:18 mitch Exp $ +# $Id: s9y_poster_import.pl,v 1.2 2007-09-30 16:44:03 mitch Exp $ use strict; use warnings; use Time::Local; use Data::Dumper; use DBI; my $posterdir = $ARGV[0]; die "needs poster data directory as first argument" unless defined $posterdir and $posterdir ne ''; # get database connection my $dbh = DBI->connect( 'DBI:mysql:database=serendipity;host=localhost;port=3306', 'serendipity', 'ihego906', {'PrintError' => 1, 'PrintWarn' => 1, 'ShowErrorStatement' => 1, }, # {'RaiseError' => 1} ); # use utf8 $dbh->do('SET NAMES utf8'); # read categories my %category; open CATEGORY, '<', "$posterdir/../categories" or die "can't open `$posterdir/../categories': $1"; while (my $line = <CATEGORY>) { my ($short, $name, undef) = split /:/, $line, 3; $category{$short} = $name; } close CATEGORY or die "can't open `$posterdir/../categories': $1"; # read entries opendir ENTRY, $posterdir or die "can't opendir `$posterdir': $!"; my @entry = sort grep { -d "$posterdir/$_" and $_ =~ /^\d{14}$/ } readdir(ENTRY); closedir ENTRY or die "can't closedir `$posterdir': $!"; print @entry . " entries found.\n"; # process entries foreach my $entry (@entry) { print "entry $entry...\n"; my $dir = "$posterdir/$entry"; my $line; my %entry; # read comments opendir COMMENT, "$dir/comments/" or die "can't opendir `$dir/comments/': $!"; my @comment = sort grep { -f "$dir/comments/$_" and $_ =~ /^\d{14}$/ } readdir(COMMENT); closedir COMMENT or die "can't closedir `$dir/comments/': $!"; print " " . @comment . " comments found.\n"; # read trackbacks opendir TRACKBACK, "$dir/trackbacks/" or die "can't opendir `$dir/trackbacks/': $!"; my @trackback = sort grep { -f "$dir/trackbacks/$_" and $_ =~ /^\d{14}$/ } readdir(TRACKBACK); closedir TRACKBACK or die "can't closedir `$dir/trackbacks/': $!"; print " " . @trackback . " trackbacks found.\n"; # process entry ## TODO: localtime or gmtime?? - $entry{TIMESTAMP} = timegm( + $entry{TIMESTAMP} = timelocal( substr($entry, 12, 2), substr($entry, 10, 2), substr($entry, 8, 2), substr($entry, 6, 2), substr($entry, 4, 2)-1, substr($entry, 0, 4) ); open ENTRY, '<', "$dir/post" or die "can't open `$dir/post': $!"; ## the first three lines contain administrative data (AUTHOR, CATEGORY, TITLE) for (1..3) { $line = <ENTRY>; chomp $line; if ($line =~ /^([A-Z_]+): (.*)$/) { $entry{$1} = $2; } } while ($line = <ENTRY>) { chomp $line; $entry{BODY} .= $line .' '; } $entry{BODY} =~ s/\s+$//; close ENTRY or die "can't close `$dir/post': $!"; # process comments $entry{COMMENTS} = []; foreach my $comment (sort @comment) { my %comment; ## TODO: localtime or gmtime?? - $comment{TIMESTAMP} = timegm( + $comment{TIMESTAMP} = timelocal( substr($comment, 12, 2), substr($comment, 10, 2), substr($comment, 8, 2), substr($comment, 6, 2), substr($comment, 4, 2)-1, substr($comment, 0, 4) ); open COMMENT, '<', "$dir/comments/$comment" or die "can't open `$dir/comments/$comment': $!"; $line = <COMMENT>; chomp $line; if ($line =~ /^AUTHOR: (.*)$/) { $line = $1; if ($line =~ /^(.*?):(.*)$/) { $comment{AUTHOR} = $1; $comment{URL} = $2 unless $2 =~ m|^http\\://www.cgarbs.de/blog/index.php/|; } else { $comment{AUTHOR} = $line; } } while ($line = <COMMENT>) { chomp $line; $comment{BODY} .= $line .' '; } $comment{BODY} =~ s/\s+$//; close COMMENT or die "can't close `$dir/comments/$comment': $!"; push @{$entry{COMMENTS}}, {%comment}; } # process trackbacks $entry{TRACKBACKS} = []; foreach my $trackback (sort @trackback) { my %trackback; ## TODO: localtime or gmtime?? - $trackback{TIMESTAMP} = timegm( + $trackback{TIMESTAMP} = timelocal( substr($trackback, 12, 2), substr($trackback, 10, 2), substr($trackback, 8, 2), substr($trackback, 6, 2), substr($trackback, 4, 2)-1, substr($trackback, 0, 4) ); open TRACKBACK, '<', "$dir/trackbacks/$trackback" or die "can't open `$dir/trackbacks/$trackback': $!"; ## the first three lines contain administrative data (URL, TITLE, BLOG_NAME) for (1..3) { $line = <TRACKBACK>; chomp $line; if ($line =~ /^([A-Z_]+): (.*)$/) { $trackback{$1} = $2; } } while ($line = <TRACKBACK>) { chomp $line; $trackback{BODY} .= $line .' '; } $trackback{BODY} =~ s/\s+$//; close TRACKBACK or die "can't close `$dir/trackbacks/$trackback': $!"; push @{$entry{TRACKBACKS}}, {%trackback}; } print "\n"; ## next unless @{$entry{TRACKBACKS}} > 0 and @{$entry{COMMENTS}} > 0; # save entry my $insert_entry = sprintf('INSERT INTO serendipity_entries (title, timestamp, body, comments, trackbacks, author, authorid ) VALUES ( %s, %d, %s, %d, %d, %s, %d )', $dbh->quote($entry{TITLE}), $entry{TIMESTAMP} + 0, $dbh->quote($entry{BODY}), 0, 0, $dbh->quote($entry{AUTHOR}), 1); # print "$insert_entry\n"; $dbh->do($insert_entry); my $entryid = $dbh->last_insert_id(undef, undef, undef, undef); # save category if (exists $category{$entry{CATEGORY}}) { my $get_category = $dbh->prepare('SELECT categoryid FROM serendipity_category WHERE category_name = '.$dbh->quote($category{$entry{CATEGORY}})); $get_category->execute(); if (my $ref = $get_category->fetchrow_hashref()) { my $insert_category = sprintf('INSERT INTO serendipity_entrycat (entryid, categoryid) VALUES ( %d, %d )', $entryid, $ref->{categoryid} + 0); # print "$insert_category\n"; $dbh->do($insert_category); } } # save comments foreach my $comment (@{$entry{COMMENTS}}) { my $insert_comment = sprintf('INSERT INTO serendipity_comments (entry_id, timestamp, author, url, body, type, status) VALUES ( %d, %d, %s, %s, %s, %s, %s )', $entryid, $comment->{TIMESTAMP}, $dbh->quote($comment->{AUTHOR}), exists $comment->{URL} ? $dbh->quote($comment->{URL}) : 'NULL', $dbh->quote($comment->{BODY}), $dbh->quote('NORMAL'), $dbh->quote('pending')); # print "$insert_comment\n"; $dbh->do($insert_comment); } # save trackbacks foreach my $trackback (@{$entry{TRACKBACKS}}) { my $insert_trackback = sprintf('INSERT INTO serendipity_comments (entry_id, timestamp, author, url, body, type, status) VALUES ( %d, %d, %s, %s, %s, %s, %s )', $entryid, $trackback->{TIMESTAMP}, $dbh->quote($trackback->{BLOG_NAME}), exists $trackback->{URL} ? $dbh->quote($trackback->{URL}) : 'NULL', $dbh->quote($trackback->{BODY}), $dbh->quote('TRACKBACK'), $dbh->quote('pending')); # print "$insert_trackback\n"; $dbh->do($insert_trackback); } ## exit; } __DATA__ # restore after test run delete from serendipity_comments where entry_id != 1; delete from serendipity_entries where id != 1; delete from serendipity_entrycat where entryid != 1; delete from serendipity_references where entry_id != 1;
mmitch/s9y_poster_import
d2df1dab9bfa4dcc549984ffbb70dc05ba1f4aa7
Initial revision
diff --git a/s9y_poster_import.pl b/s9y_poster_import.pl new file mode 100755 index 0000000..9280c76 --- /dev/null +++ b/s9y_poster_import.pl @@ -0,0 +1,237 @@ +#!/usr/bin/perl +# $Id: s9y_poster_import.pl,v 1.1 2007-09-30 16:36:18 mitch Exp $ +use strict; +use warnings; +use Time::Local; +use Data::Dumper; +use DBI; + +my $posterdir = $ARGV[0]; + +die "needs poster data directory as first argument" unless defined $posterdir and $posterdir ne ''; + +# get database connection +my $dbh = DBI->connect( + 'DBI:mysql:database=serendipity;host=localhost;port=3306', + 'serendipity', + 'ihego906', + {'PrintError' => 1, + 'PrintWarn' => 1, + 'ShowErrorStatement' => 1, + + }, + # {'RaiseError' => 1} + ); + +# use utf8 +$dbh->do('SET NAMES utf8'); + +# read categories +my %category; +open CATEGORY, '<', "$posterdir/../categories" or die "can't open `$posterdir/../categories': $1"; +while (my $line = <CATEGORY>) { + my ($short, $name, undef) = split /:/, $line, 3; + $category{$short} = $name; +} +close CATEGORY or die "can't open `$posterdir/../categories': $1"; + +# read entries +opendir ENTRY, $posterdir or die "can't opendir `$posterdir': $!"; +my @entry = sort grep { -d "$posterdir/$_" and $_ =~ /^\d{14}$/ } readdir(ENTRY); +closedir ENTRY or die "can't closedir `$posterdir': $!"; +print @entry . " entries found.\n"; + + +# process entries +foreach my $entry (@entry) { + print "entry $entry...\n"; + + my $dir = "$posterdir/$entry"; + my $line; + my %entry; + + # read comments + opendir COMMENT, "$dir/comments/" or die "can't opendir `$dir/comments/': $!"; + my @comment = sort grep { -f "$dir/comments/$_" and $_ =~ /^\d{14}$/ } readdir(COMMENT); + closedir COMMENT or die "can't closedir `$dir/comments/': $!"; + print " " . @comment . " comments found.\n"; + + # read trackbacks + opendir TRACKBACK, "$dir/trackbacks/" or die "can't opendir `$dir/trackbacks/': $!"; + my @trackback = sort grep { -f "$dir/trackbacks/$_" and $_ =~ /^\d{14}$/ } readdir(TRACKBACK); + closedir TRACKBACK or die "can't closedir `$dir/trackbacks/': $!"; + print " " . @trackback . " trackbacks found.\n"; + + # process entry + ## TODO: localtime or gmtime?? + $entry{TIMESTAMP} = timegm( + substr($entry, 12, 2), + substr($entry, 10, 2), + substr($entry, 8, 2), + substr($entry, 6, 2), + substr($entry, 4, 2)-1, + substr($entry, 0, 4) + ); + + open ENTRY, '<', "$dir/post" or die "can't open `$dir/post': $!"; + ## the first three lines contain administrative data (AUTHOR, CATEGORY, TITLE) + for (1..3) { + $line = <ENTRY>; + chomp $line; + if ($line =~ /^([A-Z_]+): (.*)$/) { + $entry{$1} = $2; + } + } + while ($line = <ENTRY>) { + chomp $line; + $entry{BODY} .= $line .' '; + } + $entry{BODY} =~ s/\s+$//; + close ENTRY or die "can't close `$dir/post': $!"; + + # process comments + $entry{COMMENTS} = []; + foreach my $comment (sort @comment) { + my %comment; + ## TODO: localtime or gmtime?? + $comment{TIMESTAMP} = timegm( + substr($comment, 12, 2), + substr($comment, 10, 2), + substr($comment, 8, 2), + substr($comment, 6, 2), + substr($comment, 4, 2)-1, + substr($comment, 0, 4) + ); + + open COMMENT, '<', "$dir/comments/$comment" or die "can't open `$dir/comments/$comment': $!"; + $line = <COMMENT>; + chomp $line; + if ($line =~ /^AUTHOR: (.*)$/) { + $line = $1; + if ($line =~ /^(.*?):(.*)$/) { + $comment{AUTHOR} = $1; + $comment{URL} = $2 unless $2 =~ m|^http\\://www.cgarbs.de/blog/index.php/|; + } else { + $comment{AUTHOR} = $line; + } + } + while ($line = <COMMENT>) { + chomp $line; + $comment{BODY} .= $line .' '; + } + $comment{BODY} =~ s/\s+$//; + close COMMENT or die "can't close `$dir/comments/$comment': $!"; + push @{$entry{COMMENTS}}, {%comment}; + } + + # process trackbacks + $entry{TRACKBACKS} = []; + foreach my $trackback (sort @trackback) { + my %trackback; + + ## TODO: localtime or gmtime?? + $trackback{TIMESTAMP} = timegm( + substr($trackback, 12, 2), + substr($trackback, 10, 2), + substr($trackback, 8, 2), + substr($trackback, 6, 2), + substr($trackback, 4, 2)-1, + substr($trackback, 0, 4) + ); + + open TRACKBACK, '<', "$dir/trackbacks/$trackback" or die "can't open `$dir/trackbacks/$trackback': $!"; + ## the first three lines contain administrative data (URL, TITLE, BLOG_NAME) + for (1..3) { + $line = <TRACKBACK>; + chomp $line; + if ($line =~ /^([A-Z_]+): (.*)$/) { + $trackback{$1} = $2; + } + } + while ($line = <TRACKBACK>) { + chomp $line; + $trackback{BODY} .= $line .' '; + } + $trackback{BODY} =~ s/\s+$//; + close TRACKBACK or die "can't close `$dir/trackbacks/$trackback': $!"; + push @{$entry{TRACKBACKS}}, {%trackback}; + } + + print "\n"; + + +## next unless @{$entry{TRACKBACKS}} > 0 and @{$entry{COMMENTS}} > 0; + + # save entry + my $insert_entry = + sprintf('INSERT INTO serendipity_entries (title, timestamp, body, comments, trackbacks, author, authorid ) VALUES ( %s, %d, %s, %d, %d, %s, %d )', + $dbh->quote($entry{TITLE}), + $entry{TIMESTAMP} + 0, + $dbh->quote($entry{BODY}), + 0, + 0, + $dbh->quote($entry{AUTHOR}), + 1); + +# print "$insert_entry\n"; + $dbh->do($insert_entry); + + my $entryid = $dbh->last_insert_id(undef, undef, undef, undef); + + # save category + if (exists $category{$entry{CATEGORY}}) { + + my $get_category = + $dbh->prepare('SELECT categoryid FROM serendipity_category WHERE category_name = '.$dbh->quote($category{$entry{CATEGORY}})); + $get_category->execute(); + if (my $ref = $get_category->fetchrow_hashref()) { + my $insert_category = + sprintf('INSERT INTO serendipity_entrycat (entryid, categoryid) VALUES ( %d, %d )', $entryid, $ref->{categoryid} + 0); + # print "$insert_category\n"; + $dbh->do($insert_category); + } + } + + # save comments + foreach my $comment (@{$entry{COMMENTS}}) { + my $insert_comment = + sprintf('INSERT INTO serendipity_comments (entry_id, timestamp, author, url, body, type, status) VALUES ( %d, %d, %s, %s, %s, %s, %s )', + $entryid, + $comment->{TIMESTAMP}, + $dbh->quote($comment->{AUTHOR}), + exists $comment->{URL} ? $dbh->quote($comment->{URL}) : 'NULL', + $dbh->quote($comment->{BODY}), + $dbh->quote('NORMAL'), + $dbh->quote('pending')); + # print "$insert_comment\n"; + $dbh->do($insert_comment); + } + + # save trackbacks + foreach my $trackback (@{$entry{TRACKBACKS}}) { + my $insert_trackback = + sprintf('INSERT INTO serendipity_comments (entry_id, timestamp, author, url, body, type, status) VALUES ( %d, %d, %s, %s, %s, %s, %s )', + $entryid, + $trackback->{TIMESTAMP}, + $dbh->quote($trackback->{BLOG_NAME}), + exists $trackback->{URL} ? $dbh->quote($trackback->{URL}) : 'NULL', + $dbh->quote($trackback->{BODY}), + $dbh->quote('TRACKBACK'), + $dbh->quote('pending')); + # print "$insert_trackback\n"; + $dbh->do($insert_trackback); + } + +## exit; + +} + +__DATA__ + +# restore after test run + +delete from serendipity_comments where entry_id != 1; +delete from serendipity_entries where id != 1; +delete from serendipity_entrycat where entryid != 1; +delete from serendipity_references where entry_id != 1; +
oraccha/jnperf
d4b5c838ccc99d6522b2d844859ec1fc0bd4b6b4
Ditto.
diff --git a/RecvFile.java b/RecvFile.java index 738a89b..840518c 100644 --- a/RecvFile.java +++ b/RecvFile.java @@ -1,38 +1,39 @@ /* - * SendFile.java + * RecvFile.java + * Usage: java RecvFile [-port <port>] */ import java.io.*; import java.nio.*; import java.nio.channels.*; import java.net.*; public class RecvFile { public static void main(String[] args) { int port = 10000; for (int i = 0; i < args.length; i++) { if ("-port".equals(args[i])) port = Integer.parseInt(args[++i]); } try { ServerSocketChannel serverChan = ServerSocketChannel.open(); serverChan.socket().bind(new InetSocketAddress(port)); while (true) { SocketChannel chan = serverChan.accept(); DataInputStream dis = new DataInputStream(chan.socket().getInputStream()); long len = dis.readLong(); String fname = dis.readUTF(); FileOutputStream dst = new FileOutputStream(new File(fname)); FileChannel out = dst.getChannel(); out.transferFrom(chan, 0, len); } } catch (IOException e) { e.printStackTrace(); } } }
oraccha/jnperf
d1453ee85782904d3f12ce03456ae244488940f0
Add channel test programs.
diff --git a/RecvFile.java b/RecvFile.java new file mode 100644 index 0000000..738a89b --- /dev/null +++ b/RecvFile.java @@ -0,0 +1,38 @@ +/* + * SendFile.java + */ +import java.io.*; +import java.nio.*; +import java.nio.channels.*; +import java.net.*; + +public class RecvFile { + public static void main(String[] args) { + int port = 10000; + + for (int i = 0; i < args.length; i++) { + if ("-port".equals(args[i])) + port = Integer.parseInt(args[++i]); + } + + try { + ServerSocketChannel serverChan = ServerSocketChannel.open(); + serverChan.socket().bind(new InetSocketAddress(port)); + + while (true) { + SocketChannel chan = serverChan.accept(); + DataInputStream dis = new DataInputStream(chan.socket().getInputStream()); + long len = dis.readLong(); + String fname = dis.readUTF(); + + FileOutputStream dst = new FileOutputStream(new File(fname)); + FileChannel out = dst.getChannel(); + + out.transferFrom(chan, 0, len); + } + + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/SendFile.java b/SendFile.java new file mode 100644 index 0000000..b832312 --- /dev/null +++ b/SendFile.java @@ -0,0 +1,57 @@ +/* + * SendFile.java + * Usage: java SendFile [-port <port>] filename address + */ +import java.io.*; +import java.nio.*; +import java.nio.channels.*; +import java.net.*; + +public class SendFile { + public static void main(String[] args) { + int port = 10000; + + int i; + for (i = 0; i < args.length; i++) { + if ("-port".equals(args[i])) + port = Integer.parseInt(args[++i]); + else + break; + } + String filename = args[i++]; + String addr = args[i++]; + + try { + File file = new File(filename); + FileInputStream src = new FileInputStream(file); + + try { + FileChannel in = src.getChannel(); + + SocketChannel out = SocketChannel.open(); + out.connect(new InetSocketAddress(InetAddress.getByName(addr), + port)); + DataOutputStream dos = new DataOutputStream(out.socket().getOutputStream()); + long len = in.size(); + dos.writeLong(len); + dos.writeUTF(file.getName()); + + long start = System.currentTimeMillis(); + + in.transferTo(0, len, out); + + long end = System.currentTimeMillis(); + long elapse = end - start; + double bw = ((double)len * 1000.0d) / (double)elapse; + System.out.println(len + " " + bw + " Bytes/sec (" + + elapse + " msec)"); + + } catch (IOException e) { + e.printStackTrace(); + } + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } +} + diff --git a/Sink.java b/Sink.java index 1a83a64..5f9028c 100644 --- a/Sink.java +++ b/Sink.java @@ -1,74 +1,76 @@ /* * Sink.java * Usage: java Sink [-port <port>] */ import java.io.*; import java.net.*; public class Sink { int port; public Sink(int port) { this.port = port; } public void run() { try { ServerSocket serverSock = new ServerSocket(port); while (true) { Socket sock = serverSock.accept(); new SinkThread(sock).start(); } } catch (IOException e) { System.out.println(e); System.exit(-1); } } public static void main(String[] args) { int port = 10000; for (int i = 0; i < args.length; i++) { if ("-port".equals(args[i])) port = Integer.parseInt(args[++i]); + else + break; } Sink sink = new Sink(port); sink.run(); } } class SinkThread extends Thread { private Socket sock; public SinkThread(Socket sock) { this.sock = sock; } public void start() { try { DataInputStream in = new DataInputStream(sock.getInputStream()); DataOutputStream out = new DataOutputStream(sock.getOutputStream()); try { int len = in.readInt(); int iter = in.readInt(); byte[] buf = new byte[len]; for (int i = 0; i < iter; i++) in.readFully(buf); out.writeInt(0); /* sync */ buf = null; } finally { out.close(); in.close(); sock.close(); } } catch (IOException e) { e.printStackTrace(); } } }
oraccha/jnperf
86f9b310c71b4f1177d456210f1a7d418e4dbada
Fix the excaption handling.
diff --git a/Bulk.java b/Bulk.java index 30dba5d..862c55c 100644 --- a/Bulk.java +++ b/Bulk.java @@ -1,88 +1,97 @@ +/* + * Bulk.java + * Usage: java Bulk [-port <port>] [-len <len1,len2,...>] [-iter <iter>] address + */ import java.io.*; import java.net.*; public class Bulk { String addr; int port; public Bulk(String addr, int port) { this.addr = addr; this.port = port; } - public long run(int len, int iter) { + public long run(int len, int iter) throws IOException { byte[] buf = new byte[len]; for (int i = 0; i < len; i++) { buf[i] = (byte)i; } try { - InetAddress sink = InetAddress.getByName(addr); - Socket sock = new Socket(sink, port); + Socket sock = new Socket(InetAddress.getByName(addr), port); DataInputStream in = new DataInputStream(sock.getInputStream()); DataOutputStream out = new DataOutputStream(sock.getOutputStream()); + try { + out.writeInt(len); + out.writeInt(iter); - out.writeInt(len); - out.writeInt(iter); + long start = System.currentTimeMillis(); - long start = System.currentTimeMillis(); + for (int i = 0; i < iter; i++) + out.write(buf, 0, buf.length); - for (int i = 0; i < iter; i++) - out.write(buf, 0, buf.length); + in.readInt(); /* sync */ + out.flush(); - in.readInt(); /* sync */ - out.flush(); + long end = System.currentTimeMillis(); - long end = System.currentTimeMillis(); - - sock.close(); - return end - start; + return end - start; + } finally { + out.close(); + in.close(); + sock.close(); + } } catch (IOException e) { - System.out.println(e); - System.exit(-1); - return 0; /* never here */ + throw e; } } public static void main(String[] args) { int port = 10000; String[] lens = {}; int iter = 0; long elapse; String addr = "localhost"; boolean isest = false; for (int i = 0; i < args.length; i++) { if ("-port".equals(args[i])) { port = Integer.parseInt(args[++i]); } else if ("-len".equals(args[i])) { lens = args[++i].split(",", -1); } else if ("-iter".equals(args[i])) { iter = Integer.parseInt(args[++i]); } else { addr = args[i]; } } - Bulk bulk = new Bulk(addr, port); + try { + Bulk bulk = new Bulk(addr, port); + + if (iter == 0) + isest = true; - if (iter == 0) - isest = true; + for (String l : lens) { + int len = Integer.parseInt(l); - for (String l : lens) { - int len = Integer.parseInt(l); + if (isest) { + /* iter is roughly estimated at 10 seconds. */ + elapse = bulk.run(len, 100); + iter = (int)Math.ceil(1000000d / (double)elapse); + } - if (isest) { - /* iter is roughly estimated at 10 seconds. */ - elapse = bulk.run(len, 100); - iter = (int)Math.ceil(1000000d / (double)elapse); + elapse = bulk.run(len, iter); + double bw = ((double)len * (double)iter * 1000.0d) / (double)elapse; + System.out.println(len + " " + iter + " " + bw + " Bytes/sec (" + + elapse + " msec)"); } - - elapse = bulk.run(len, iter); - double bw = ((double)len * (double)iter * 1000.0d) / (double)elapse; - System.out.println(len + " " + iter + " " + bw + " Bytes/sec (" - + elapse + " msec)"); + } catch (IOException e) { + e.printStackTrace(); } } } \ No newline at end of file diff --git a/Sink.java b/Sink.java index 1c9dbb8..1a83a64 100644 --- a/Sink.java +++ b/Sink.java @@ -1,64 +1,74 @@ +/* + * Sink.java + * Usage: java Sink [-port <port>] + */ import java.io.*; import java.net.*; public class Sink { int port; public Sink(int port) { this.port = port; } public void run() { try { ServerSocket serverSock = new ServerSocket(port); while (true) { Socket sock = serverSock.accept(); new SinkThread(sock).start(); } } catch (IOException e) { System.out.println(e); System.exit(-1); } } public static void main(String[] args) { int port = 10000; for (int i = 0; i < args.length; i++) { if ("-port".equals(args[i])) port = Integer.parseInt(args[++i]); } Sink sink = new Sink(port); sink.run(); } } class SinkThread extends Thread { private Socket sock; public SinkThread(Socket sock) { this.sock = sock; } public void start() { try { DataInputStream in = new DataInputStream(sock.getInputStream()); DataOutputStream out = new DataOutputStream(sock.getOutputStream()); - int len = in.readInt(); - int iter = in.readInt(); - byte[] buf = new byte[len]; + try { + int len = in.readInt(); + int iter = in.readInt(); + byte[] buf = new byte[len]; - for (int i = 0; i < iter; i++) - in.readFully(buf); + for (int i = 0; i < iter; i++) + in.readFully(buf); - out.writeInt(0); /* sync */ - buf = null; + out.writeInt(0); /* sync */ + + buf = null; + } finally { + out.close(); + in.close(); + sock.close(); + } } catch (IOException e) { - System.out.println(e); - return; + e.printStackTrace(); } } }
oraccha/jnperf
3f09158fadd9d42803339d6ed5141c48657d96fa
Add some command line parameters.
diff --git a/Bulk.java b/Bulk.java index e277b42..30dba5d 100644 --- a/Bulk.java +++ b/Bulk.java @@ -1,42 +1,88 @@ import java.io.*; import java.net.*; public class Bulk { - public static void main(String[] args) { + String addr; + int port; - try { - InetAddress sink = InetAddress.getByName(args[0]); - int len = Integer.parseInt(args[1]); - int iter = Integer.parseInt(args[2]); - byte[] buf = new byte[len]; + public Bulk(String addr, int port) { + this.addr = addr; + this.port = port; + } - for (int i = 0; i < len; i++) { - buf[i] = (byte)i; - } + public long run(int len, int iter) { + byte[] buf = new byte[len]; + + for (int i = 0; i < len; i++) { + buf[i] = (byte)i; + } - Socket sock = new Socket(sink, 10000); + try { + InetAddress sink = InetAddress.getByName(addr); + Socket sock = new Socket(sink, port); DataInputStream in = new DataInputStream(sock.getInputStream()); DataOutputStream out = new DataOutputStream(sock.getOutputStream()); out.writeInt(len); out.writeInt(iter); long start = System.currentTimeMillis(); - for (int i = 0; i < iter; i++) { + for (int i = 0; i < iter; i++) out.write(buf, 0, buf.length); - out.flush(); - } + in.readInt(); /* sync */ - sock.close(); + out.flush(); long end = System.currentTimeMillis(); - double bw = ((double)len * (double)iter * 1000.0) / (double)(end - start); - System.out.println(len + " " + bw + " Bytes/sec (" + (end - start) + " msec)"); + sock.close(); + return end - start; } catch (IOException e) { System.out.println(e); System.exit(-1); + return 0; /* never here */ + } + } + + public static void main(String[] args) { + int port = 10000; + String[] lens = {}; + int iter = 0; + long elapse; + String addr = "localhost"; + boolean isest = false; + + for (int i = 0; i < args.length; i++) { + if ("-port".equals(args[i])) { + port = Integer.parseInt(args[++i]); + } else if ("-len".equals(args[i])) { + lens = args[++i].split(",", -1); + } else if ("-iter".equals(args[i])) { + iter = Integer.parseInt(args[++i]); + } else { + addr = args[i]; + } + } + + Bulk bulk = new Bulk(addr, port); + + if (iter == 0) + isest = true; + + for (String l : lens) { + int len = Integer.parseInt(l); + + if (isest) { + /* iter is roughly estimated at 10 seconds. */ + elapse = bulk.run(len, 100); + iter = (int)Math.ceil(1000000d / (double)elapse); + } + + elapse = bulk.run(len, iter); + double bw = ((double)len * (double)iter * 1000.0d) / (double)elapse; + System.out.println(len + " " + iter + " " + bw + " Bytes/sec (" + + elapse + " msec)"); } } } \ No newline at end of file diff --git a/Sink.java b/Sink.java index fbeb91c..1c9dbb8 100644 --- a/Sink.java +++ b/Sink.java @@ -1,47 +1,64 @@ import java.io.*; import java.net.*; public class Sink { - public static void main(String[] args) { + int port; + + public Sink(int port) { + this.port = port; + } + public void run() { try { - ServerSocket serverSock = new ServerSocket(10000); + ServerSocket serverSock = new ServerSocket(port); while (true) { Socket sock = serverSock.accept(); new SinkThread(sock).start(); } } catch (IOException e) { System.out.println(e); System.exit(-1); } } + + public static void main(String[] args) { + int port = 10000; + + for (int i = 0; i < args.length; i++) { + if ("-port".equals(args[i])) + port = Integer.parseInt(args[++i]); + } + + Sink sink = new Sink(port); + sink.run(); + } } class SinkThread extends Thread { private Socket sock; public SinkThread(Socket sock) { this.sock = sock; } public void start() { try { DataInputStream in = new DataInputStream(sock.getInputStream()); DataOutputStream out = new DataOutputStream(sock.getOutputStream()); int len = in.readInt(); int iter = in.readInt(); byte[] buf = new byte[len]; - for (int i = 0; i < iter; i++) { + for (int i = 0; i < iter; i++) in.readFully(buf); - } + out.writeInt(0); /* sync */ buf = null; } catch (IOException e) { System.out.println(e); - System.exit(-1); + return; } } }
oraccha/jnperf
4c5691559da5b19bf5c4b90b35f3d38cf1855794
Initial checkin.
diff --git a/Bulk.java b/Bulk.java new file mode 100644 index 0000000..e277b42 --- /dev/null +++ b/Bulk.java @@ -0,0 +1,42 @@ +import java.io.*; +import java.net.*; + +public class Bulk { + public static void main(String[] args) { + + try { + InetAddress sink = InetAddress.getByName(args[0]); + int len = Integer.parseInt(args[1]); + int iter = Integer.parseInt(args[2]); + byte[] buf = new byte[len]; + + for (int i = 0; i < len; i++) { + buf[i] = (byte)i; + } + + Socket sock = new Socket(sink, 10000); + DataInputStream in = new DataInputStream(sock.getInputStream()); + DataOutputStream out = new DataOutputStream(sock.getOutputStream()); + + out.writeInt(len); + out.writeInt(iter); + + long start = System.currentTimeMillis(); + + for (int i = 0; i < iter; i++) { + out.write(buf, 0, buf.length); + out.flush(); + } + in.readInt(); /* sync */ + sock.close(); + + long end = System.currentTimeMillis(); + + double bw = ((double)len * (double)iter * 1000.0) / (double)(end - start); + System.out.println(len + " " + bw + " Bytes/sec (" + (end - start) + " msec)"); + } catch (IOException e) { + System.out.println(e); + System.exit(-1); + } + } +} \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..5b6e7c6 --- /dev/null +++ b/LICENSE @@ -0,0 +1,340 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + <signature of Ty Coon>, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/README b/README new file mode 100644 index 0000000..4695a5f --- /dev/null +++ b/README @@ -0,0 +1,4 @@ +jnperf: TCP bandwidth measurement tool written in Java + +Copyright (C) 2009 oraccha <http://github.com/oraccha/> + diff --git a/Sink.java b/Sink.java new file mode 100644 index 0000000..fbeb91c --- /dev/null +++ b/Sink.java @@ -0,0 +1,47 @@ +import java.io.*; +import java.net.*; + +public class Sink { + public static void main(String[] args) { + + try { + ServerSocket serverSock = new ServerSocket(10000); + + while (true) { + Socket sock = serverSock.accept(); + new SinkThread(sock).start(); + } + } catch (IOException e) { + System.out.println(e); + System.exit(-1); + } + } +} + +class SinkThread extends Thread { + private Socket sock; + + public SinkThread(Socket sock) { + this.sock = sock; + } + + public void start() { + try { + DataInputStream in = new DataInputStream(sock.getInputStream()); + DataOutputStream out = new DataOutputStream(sock.getOutputStream()); + + int len = in.readInt(); + int iter = in.readInt(); + byte[] buf = new byte[len]; + + for (int i = 0; i < iter; i++) { + in.readFully(buf); + } + out.writeInt(0); /* sync */ + buf = null; + } catch (IOException e) { + System.out.println(e); + System.exit(-1); + } + } +} diff --git a/build.xml b/build.xml new file mode 100644 index 0000000..4f61ef9 --- /dev/null +++ b/build.xml @@ -0,0 +1,6 @@ +<?xml version="1.0"?> +<project name="Jnperf" default="default"> + <target name="default"> + <javac srcdir="." destdir="."/> + </target> +</project>
harking/sort-helper
67142bbd15c0dc6735dacc9e59666971587c4c00
Adding sort_helper.rb to repo.
diff --git a/sort_helper.rb b/sort_helper.rb new file mode 100755 index 0000000..288e2dc --- /dev/null +++ b/sort_helper.rb @@ -0,0 +1,195 @@ +# Helpers to sort tables using clickable column headers. +# +# Author: Stuart Rackham <[email protected]>, March 2005. +# Author: George Harkin <[email protected]>, March 2006 +# (Added multiple table sorting) +# License: This source code is released under the MIT license. +# +# - Consecutive clicks toggle the column's sort order. +# - Sort state is maintained by a session hash entry. +# - Icon image identifies sort column and state. +# - Typically used in conjunction with the Pagination module. +# +# Example code snippets: +# +# Controller: +# +# helper :sort +# include SortHelper +# +# def list +# sort_init 'last_name' +# sort_update +# @items = Contact.find(:all, :conditions => sort_clause) +# end +# +# Controller with paginator: +# +# helper :sort +# include SortHelper +# +# def list +# sort_init 'last_name' +# sort_update +# @contact_pages, @items = paginate(:contacts, +# :order_by => sort_clause, +# :per_page => 10) +# end +# +# View (table header in list.rhtml): +# +# <thead> +# <tr> +# <%= sort_header_tag('id', :title => 'Sort by contact ID') %> +# <%= sort_header_tag('last_name', :text => 'Name') %> +# <%= sort_header_tag('phone') %> +# <%= sort_header_tag('address', :width => 200) %> +# </tr> +# </thead> +# +# - The ascending and descending sort icon images are sort_asc.png and +# sort_desc.png and reside in the application's images directory. +# - Introduces instance variables: @sort_name, @sort_default. +# - Introduces params :sort_key and :sort_order. +# +# History +# ------- +# 2006-04-04: Version 1.0.2 +# - Tidied up examples. +# - Changed older @params and @session style to params and sessions. +# 2006-01-19: Version 1.0.1 +# - sort_init() accepts options hash. +# - sort_init() :icons_dir option added. +# 2005-03-26: Version 1.0.0 +# +module SortHelper + + + # Initializes the default sort column (default_key) with the following + # options: + # + # - :default_order -- the default sort order 'asc' or 'desc'. Defaults to + # 'asc'. + # - :name -- the name of the session hash entry that stores the sort state. + # Defaults to '<controller_name>_sort'. + # - :icons_dir -- directory with sort direction icons. Defaults to + # /images + # + def sort_init(default_key, options={}) + options = { :default_order => 'asc', + :name => params[:controller] + '_sort', + :icons_dir => '/images', + }.merge(options) + @sort_name = options[:name] + @sort_default = {:key => default_key, :order => options[:default_order]} + @icons_dir = options[:icons_dir] + end + + # Updates the sort state. Call this in the controller prior to calling + # sort_clause. + # + def sort_update() + if params[:sort_key] + if params[:sort_key][/\,/] # There is more than one sort column + sort = {:key => params[:sort_key].split(","), :order => params[:sort_order]} + else + sort = {:key => params[:sort_key], :order => params[:sort_order]} + end + elsif session[@sort_name] + sort = session[@sort_name] # Previous sort. + else + sort = @sort_default + end + session[@sort_name] = sort + end + + # Returns an SQL sort clause corresponding to the current sort state. + # Use this to sort the controller's table items collection. + # + def sort_clause() + if session[@sort_name][:key].is_a?(Array) + result = '' + session[@sort_name][:key].each do |key| + if session[@sort_name][:order].nil? then session[@sort_name][:order] = 'asc' end + result = result + key + ' ' + session[@sort_name][:order] + result = result + ', ' unless key == session[@sort_name][:key].last + end + elsif session[@sort_name][:key] + if session[@sort_name][:order].nil? then session[@sort_name][:order] = 'asc' end + result = session[@sort_name][:key] + ' ' + session[@sort_name][:order] + end + result if result =~ /^(([\w]+([.][\w]+)?)[\s]+(asc|desc|ASC|DESC)[,]?[\s]*)+$/i # Validate sort. + end + + # Returns a link which sorts by the named column. + # + # - column is the name of an attribute in the sorted record collection. + # - The optional text explicitly specifies the displayed link text. + # - A sort icon image is positioned to the right of the sort link. + # + def sort_link(column, text=nil) + key, order = session[@sort_name][:key], session[@sort_name][:order] + if key == column || key.is_a?(Array) && key.join(',') == column + if order.downcase == 'asc' + icon, order = 'sort_asc', 'desc' + else + icon, order = 'sort_desc', 'asc' + end + else + icon, order = nil, 'asc' + end + text = Inflector::titleize(column) unless text + + # Handle the case that the column is an array of columns + sort_key = '' + if column.is_a?(Array) + column.each do |col| + sort_key = sort_key + col + sort_key = sort_key + ',' unless column.last == col + end + else + sort_key = column + end + + if params[:search_terms] then terms = params[:search_terms] + elsif params[:search] then terms = params[:search] end + + params = {:params => {:sort_key => sort_key, :sort_order => order, :search_terms => terms}} + link_to(text, params) + + (icon ? nbsp(2) + image_tag(File.join(@icons_dir,icon)) : '') + end + + # Returns a table header <th> tag with a sort link for the named column + # attribute. + # + # Options: + # :text The displayed link name (defaults to titleized column name). + # :title The tag's 'title' attribute (defaults to 'Sort by :text'). + # + # Other options hash entries generate additional table header tag attributes. + # + # Example: + # + # <%= sort_header_tag('id', :title => 'Sort by contact ID', :width => 40) %> + # + # Renders: + # + # <th title="Sort by contact ID" width="40px"> + # <a href="/contact/list?sort_order=desc&amp;sort_key=id">Id</a> + # &nbsp;&nbsp;<img alt="Sort_asc" src="/images/sort_asc.png" /> + # </th> + # + def sort_header_tag(column, options = {}) + text = options.delete(:text) || Inflector::titleize(column.humanize) + options[:title]= "Sort by #{text}" unless options[:title] + content_tag('th', sort_link(column, text), options) + end + + private + + # Return n non-breaking spaces. + def nbsp(n) + '&nbsp;' * n + end + +end
adewale/Buzz-Chat-Bot
289855564adfa447182aae8feeaa75b572450156
Tweaked the way conditional imports are handled so that things still work on localhost
diff --git a/buzz_gae_client.py b/buzz_gae_client.py index 24d8471..041287e 100644 --- a/buzz_gae_client.py +++ b/buzz_gae_client.py @@ -1,118 +1,121 @@ # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = '[email protected]' import apiclient.discovery import logging import oauth_wrap import oauth2 as oauth import urllib -import urlparse +# Conditionally import these functions so that they work in Python 2.5 and 2.6 try: - from urlparse import parse_qs, parse_qsl, urlparse + from urlparse import parse_qs, parse_qsl except ImportError: from cgi import parse_qs, parse_qsl +from urlparse import urlparse +from urlparse import urlunparse + # TODO(ade) Replace user-agent with something specific HEADERS = { 'user-agent': 'gdata-python-v3-sample-client/0.1', 'content-type': 'application/x-www-form-urlencoded' } REQUEST_TOKEN_URL = 'https://www.google.com/accounts/OAuthGetRequestToken?domain=anonymous&scope=https://www.googleapis.com/auth/buzz' AUTHORIZE_URL = 'https://www.google.com/buzz/api/auth/OAuthAuthorizeToken?domain=anonymous&scope=https://www.googleapis.com/auth/buzz' ACCESS_TOKEN_URL = 'https://www.google.com/accounts/OAuthGetAccessToken' class Error(Exception): """Base error for this module.""" pass class RequestError(Error): """Request returned failure or unexpected data.""" pass # TODO(ade) This class is really a BuzzGaeBuilder. Rename it. class BuzzGaeClient(object): def __init__(self, consumer_key='anonymous', consumer_secret='anonymous', api_key=None): self.api_key = api_key self.consumer = oauth.Consumer(consumer_key, consumer_secret) self.consumer_key = consumer_key self.consumer_secret = consumer_secret def _make_post_request(self, client, url, parameters): resp, content = client.request(url, 'POST', headers=HEADERS, body=urllib.urlencode(parameters, True)) if resp['status'] != '200': logging.warn('Request: %s failed with status: %s. Content was: %s' % (url, resp['status'], content)) raise RequestError('Invalid response %s.' % resp['status']) return resp, content def get_request_token(self, callback_url, display_name = None): parameters = { 'oauth_callback': callback_url } if display_name is not None: parameters['xoauth_displayname'] = display_name client = oauth.Client(self.consumer) resp, content = self._make_post_request(client, REQUEST_TOKEN_URL, parameters) request_token = dict(parse_qsl(content)) return request_token def generate_authorisation_url(self, request_token): """Returns the URL the user should be redirected to in other to gain access to their account.""" - base_url = urlparse.urlparse(AUTHORIZE_URL) + base_url = urlparse(AUTHORIZE_URL) query = parse_qs(base_url.query) query['oauth_token'] = request_token['oauth_token'] logging.info(urllib.urlencode(query, True)) url = (base_url.scheme, base_url.netloc, base_url.path, base_url.params, urllib.urlencode(query, True), base_url.fragment) - authorisation_url = urlparse.urlunparse(url) + authorisation_url = urlunparse(url) return authorisation_url def upgrade_to_access_token(self, request_token, oauth_verifier): token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(oauth_verifier) client = oauth.Client(self.consumer, token) parameters = {} resp, content = self._make_post_request(client, ACCESS_TOKEN_URL, parameters) access_token = dict(parse_qsl(content)) d = { 'consumer_key' : self.consumer_key, 'consumer_secret' : self.consumer_secret } d.update(access_token) return d def build_api_client(self, oauth_params=None): if oauth_params is not None: http = oauth_wrap.get_authorised_http(oauth_params) return apiclient.discovery.build('buzz', 'v1', http=http, developerKey=self.api_key) else: return apiclient.discovery.build('buzz', 'v1', developerKey=self.api_key)
adewale/Buzz-Chat-Bot
575dd9c1614e7bd8188658844ab323af948b26dd
We lower-case the user's email address when they finish the OAuth dance and when they send us a command that uses their email address for verification. That should fix problems with users who habitually login with an email address that is in mixed-case.
diff --git a/buzz_gae_client.py b/buzz_gae_client.py index b7cb4ae..24d8471 100644 --- a/buzz_gae_client.py +++ b/buzz_gae_client.py @@ -1,118 +1,118 @@ # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = '[email protected]' import apiclient.discovery import logging import oauth_wrap import oauth2 as oauth import urllib import urlparse try: from urlparse import parse_qs, parse_qsl, urlparse except ImportError: from cgi import parse_qs, parse_qsl # TODO(ade) Replace user-agent with something specific HEADERS = { 'user-agent': 'gdata-python-v3-sample-client/0.1', 'content-type': 'application/x-www-form-urlencoded' } REQUEST_TOKEN_URL = 'https://www.google.com/accounts/OAuthGetRequestToken?domain=anonymous&scope=https://www.googleapis.com/auth/buzz' AUTHORIZE_URL = 'https://www.google.com/buzz/api/auth/OAuthAuthorizeToken?domain=anonymous&scope=https://www.googleapis.com/auth/buzz' ACCESS_TOKEN_URL = 'https://www.google.com/accounts/OAuthGetAccessToken' class Error(Exception): """Base error for this module.""" pass class RequestError(Error): """Request returned failure or unexpected data.""" pass # TODO(ade) This class is really a BuzzGaeBuilder. Rename it. class BuzzGaeClient(object): - def __init__(self, consumer_key='anonymous', consumer_secret='anonymous', api_key=None,): + def __init__(self, consumer_key='anonymous', consumer_secret='anonymous', api_key=None): self.api_key = api_key self.consumer = oauth.Consumer(consumer_key, consumer_secret) self.consumer_key = consumer_key self.consumer_secret = consumer_secret def _make_post_request(self, client, url, parameters): resp, content = client.request(url, 'POST', headers=HEADERS, body=urllib.urlencode(parameters, True)) if resp['status'] != '200': logging.warn('Request: %s failed with status: %s. Content was: %s' % (url, resp['status'], content)) raise RequestError('Invalid response %s.' % resp['status']) return resp, content def get_request_token(self, callback_url, display_name = None): parameters = { 'oauth_callback': callback_url } if display_name is not None: parameters['xoauth_displayname'] = display_name client = oauth.Client(self.consumer) resp, content = self._make_post_request(client, REQUEST_TOKEN_URL, parameters) request_token = dict(parse_qsl(content)) return request_token def generate_authorisation_url(self, request_token): """Returns the URL the user should be redirected to in other to gain access to their account.""" base_url = urlparse.urlparse(AUTHORIZE_URL) query = parse_qs(base_url.query) query['oauth_token'] = request_token['oauth_token'] logging.info(urllib.urlencode(query, True)) url = (base_url.scheme, base_url.netloc, base_url.path, base_url.params, urllib.urlencode(query, True), base_url.fragment) authorisation_url = urlparse.urlunparse(url) return authorisation_url def upgrade_to_access_token(self, request_token, oauth_verifier): token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(oauth_verifier) client = oauth.Client(self.consumer, token) parameters = {} resp, content = self._make_post_request(client, ACCESS_TOKEN_URL, parameters) access_token = dict(parse_qsl(content)) d = { 'consumer_key' : self.consumer_key, 'consumer_secret' : self.consumer_secret } d.update(access_token) return d def build_api_client(self, oauth_params=None): if oauth_params is not None: http = oauth_wrap.get_authorised_http(oauth_params) return apiclient.discovery.build('buzz', 'v1', http=http, developerKey=self.api_key) else: return apiclient.discovery.build('buzz', 'v1', developerKey=self.api_key) diff --git a/functional_tests.py b/functional_tests.py index bd76c08..9023e41 100644 --- a/functional_tests.py +++ b/functional_tests.py @@ -1,394 +1,432 @@ # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import main +import os import unittest from gaetestbed import FunctionalTestCase from stubs import StubMessage, StubSimpleBuzzWrapper from tracker_tests import StubHubSubscriber from xmpp import Tracker, XmppHandler, extract_sender_email_address import oauth_handlers import settings class FrontPageHandlerFunctionalTest(FunctionalTestCase, unittest.TestCase): APPLICATION = main.application def test_front_page_can_be_viewed_without_being_logged_in(self): response = self.get(settings.FRONT_PAGE_HANDLER_URL) self.assertOK(response) response.mustcontain("<title>Buzz Chat Bot") response.mustcontain(settings.APP_NAME) def test_admin_profile_link_is_on_front_page(self): response = self.get(settings.FRONT_PAGE_HANDLER_URL) self.assertOK(response) response.mustcontain('href="%s"' % settings.ADMIN_PROFILE_URL) class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase): def _setup_subscription(self, sender='[email protected]',search_term='somestring'): search_term = search_term body = '%s %s' % (XmppHandler.TRACK_CMD,search_term) hub_subscriber = StubHubSubscriber() tracker = Tracker(hub_subscriber=hub_subscriber) subscription = tracker.track(sender, body) return subscription class PostsHandlerTest(BuzzChatBotFunctionalTestCase): APPLICATION = main.application def test_can_validate_hub_challenge_for_subscribe(self): subscription = self._setup_subscription() challenge = 'somechallengetoken' topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring' response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id())) self.assertOK(response) response.mustcontain(challenge) def test_can_validate_hub_challenge_for_unsubscribe(self): subscription = self._setup_subscription() subscription.delete() challenge = 'somechallengetoken' topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring' response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id())) self.assertOK(response) response.mustcontain(challenge) class StubXmppHandler(XmppHandler): def _make_wrapper(self, email_address): self.email_address = email_address return StubSimpleBuzzWrapper() class XmppHandlerTest(BuzzChatBotFunctionalTestCase): def __init__(self, methodName='runTest'): BuzzChatBotFunctionalTestCase.__init__(self, methodName) self.stub_hub_subscriber = StubHubSubscriber() self.handler = StubXmppHandler(hub_subscriber=self.stub_hub_subscriber) def test_track_command_succeeds_for_varying_combinations_of_whitespace(self): arg = 'Some day my prints will come' message = StubMessage( body='%s %s ' % (XmppHandler.TRACK_CMD,arg)) # We call the method directly here because we actually care about the object that is returned subscription = self.handler.track_command(message=message) self.assertEqual(message.message_to_send, XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (message.arg,subscription.id())) def test_invalid_symbol_command_shows_correct_error(self): command = '~' message = StubMessage(body=command) self.handler.message_received(message) self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % command in message.message_to_send, message.message_to_send) def test_unhandled_command_shows_correct_error(self): command = 'wibble' message = StubMessage(body=command) self.handler.message_received(message) self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % command in message.message_to_send, message.message_to_send) def test_track_command_fails_for_missing_term(self): message = StubMessage(body='%s ' % XmppHandler.TRACK_CMD) self.handler.message_received(message=message) self.assertTrue(XmppHandler.NOTHING_TO_TRACK_MSG in message.message_to_send, message.message_to_send) def test_untrack_command_fails_for_missing_subscription_value(self): message = StubMessage(body='%s 777' % XmppHandler.UNTRACK_CMD) self.handler.message_received(message=message) self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send) def test_untrack_command_fails_for_missing_subscription_argument(self): self._setup_subscription() message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD) self.handler.message_received(message=message) self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send) def test_untrack_command_fails_for_wrong_subscription_id(self): subscription = self._setup_subscription() id = subscription.id() + 1 message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD,id)) self.handler.message_received(message=message) self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send) def test_untrack_command_succeeds_for_valid_subscription_id(self): subscription = self._setup_subscription() id = subscription.id() message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD, id)) self.handler.message_received(message=message) self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send) def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self): subscription = self._setup_subscription() id = subscription.id() message = StubMessage(sender='[email protected]', body='%s %s' % (XmppHandler.UNTRACK_CMD,id)) self.handler.message_received(message=message) self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send) def test_untrack_command_fails_for_malformed_subscription_id(self): message = StubMessage(body='%s jaiku' % XmppHandler.UNTRACK_CMD) self.handler.message_received(message=message) self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send) def test_untrack_command_fails_for_empty_subscription_id(self): message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD) self.handler.message_received(message=message) self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send) def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self): sender1 = '[email protected]' subscription1 = self._setup_subscription(sender=sender1, search_term='searchA') sender2 = '[email protected]' subscription2 = self._setup_subscription(sender=sender2, search_term='searchB') for people in [(sender1, subscription1), (sender2, subscription2)]: sender = people[0] message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD) self.handler.message_received(message=message) subscription = people[1] self.assertTrue(str(subscription.id()) in message.message_to_send) expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id()) self.assertTrue(expected_item in message.message_to_send, message.message_to_send) def test_list_command_can_show_exactly_one_subscription(self): sender = '[email protected]' subscription = self._setup_subscription(sender=sender, search_term='searchA') message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD) self.handler.message_received(message=message) expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id()) self.assertEquals(expected_item, message.message_to_send) def test_list_command_can_handle_empty_set_of_search_terms(self): sender = '[email protected]' message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD) self.handler.message_received(message=message) expected_item = XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG self.assertTrue(len(message.message_to_send) > 0) self.assertTrue(expected_item in message.message_to_send, message.message_to_send) def test_about_command_says_what_bot_is_running(self): sender = '[email protected]' message = StubMessage(sender=sender, body='%s' % XmppHandler.ABOUT_CMD) self.handler.message_received(message=message) expected_item = 'Welcome to %[email protected]. A bot for Google Buzz' % settings.APP_NAME self.assertTrue(expected_item in message.message_to_send, message.message_to_send) def test_post_command_warns_users_with_no_oauth_token(self): sender = '[email protected]' message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD) self.handler.message_received(message=message) expected_item = 'You (%s) have not given access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL) self.assertTrue(expected_item in message.message_to_send, message.message_to_send) def test_post_command_warns_users_with_no_access_token(self): sender = '[email protected]' user_token = oauth_handlers.UserToken(email_address=sender) user_token.put() message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD) self.handler.message_received(message=message) expected_item = 'You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL) self.assertEquals(expected_item, message.message_to_send) self.assertEquals(None, oauth_handlers.UserToken.find_by_email_address(sender)) def test_post_command_posts_message_for_user_with_oauth_token(self): sender = '[email protected]' user_token = oauth_handlers.UserToken(email_address=sender) user_token.access_token_string = 'some thing that looks like an access token from a distance' user_token.put() message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD) self.handler.message_received(message=message) expected_item = 'Posted: %s' % self.handler.buzz_wrapper.url self.assertEquals(expected_item, message.message_to_send) - def test_post_command_posts_message_for_for_correct_sender(self): + def test_post_command_posts_message_for_correct_sender(self): # Using Adium format for message sender id sender = '[email protected]/Adium457EE950' email_address = extract_sender_email_address(sender) user_token = oauth_handlers.UserToken(email_address=email_address) user_token.access_token_string = 'some thing that looks like an access token from a distance' user_token.put() message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD) self.handler.message_received(message=message) self.assertEquals(email_address, self.handler.email_address) + def test_post_command_posts_message_for_sender_ignoring_case(self): + # Using Adium format for message sender id + sender = '[email protected]/Adium457EE950' + lower_email_address = extract_sender_email_address(sender).lower() + user_token = oauth_handlers.UserToken(email_address=lower_email_address) + user_token.access_token_string = 'some thing that looks like an access token from a distance' + user_token.put() + message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD) + + self.handler.message_received(message=message) + + self.assertEquals(lower_email_address, self.handler.email_address) + expected_item = 'Posted: %s' % self.handler.buzz_wrapper.url + self.assertEquals(expected_item, message.message_to_send) + + def test_post_command_posts_message_for_sender_with_mixed_case_oauth_token(self): + # Using Adium format for message sender id + sender = '[email protected]/Adium457EE950' + email_address = extract_sender_email_address(sender) + mixed_email_address = '[email protected]' + + # Note that the test simulates the OAuth dance here. + # The other tests don't need an environment that's this realistic + os.environ['USER_EMAIL'] = mixed_email_address + user_token = oauth_handlers.UserToken.create_user_token('something that looks like a request token') + user_token.put() + #user_token = oauth_handlers.UserToken(email_address=mixed_email_address) + access_token_string = 'some thing that looks like an access token from a distance' + user_token.set_access_token(access_token_string) + user_token.put() + message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD) + + self.handler.message_received(message=message) + + expected_item = 'Posted: %s' % self.handler.buzz_wrapper.url + self.assertEquals(expected_item, message.message_to_send) + def test_post_command_strips_command_from_posted_message(self): sender = '[email protected]' user_token = oauth_handlers.UserToken(email_address=sender) user_token.access_token_string = 'some thing that looks like an access token from a distance' user_token.put() message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD) self.handler.message_received(message=message) expected_item = 'some message' self.assertEquals(expected_item, self.handler.buzz_wrapper.message) def test_slash_post_command_strips_command_from_posted_message(self): sender = '[email protected]' user_token = oauth_handlers.UserToken(email_address=sender) user_token.access_token_string = 'some thing that looks like an access token from a distance' user_token.put() message = StubMessage(sender=sender, body='/%s some message' % XmppHandler.POST_CMD) self.handler.message_received(message=message) expected_item = 'some message' self.assertEquals(expected_item, self.handler.buzz_wrapper.message) def test_slash_post_gets_treated_as_post_command(self): sender = '[email protected]' user_token = oauth_handlers.UserToken(email_address=sender) user_token.access_token_string = 'some thing that looks like an access token from a distance' user_token.put() message = StubMessage(sender=sender, body='/%s some message' % XmppHandler.POST_CMD) self.handler.message_received(message=message) expected_item = 'Posted: %s' % self.handler.buzz_wrapper.url self.assertEquals(expected_item, message.message_to_send) def test_uppercase_post_gets_treated_as_post_command(self): sender = '[email protected]' user_token = oauth_handlers.UserToken(email_address=sender) user_token.access_token_string = 'some thing that looks like an access token from a distance' user_token.put() message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD.upper()) self.handler.message_received(message=message) expected_item = 'Posted: %s' % self.handler.buzz_wrapper.url self.assertEquals(expected_item, message.message_to_send) def test_slash_uppercase_post_gets_treated_as_post_command(self): sender = '[email protected]' user_token = oauth_handlers.UserToken(email_address=sender) user_token.access_token_string = 'some thing that looks like an access token from a distance' user_token.put() message = StubMessage(sender=sender, body='/%s some message' % XmppHandler.POST_CMD.upper()) self.handler.message_received(message=message) expected_item = 'Posted: %s' % self.handler.buzz_wrapper.url self.assertEquals(expected_item, message.message_to_send) def test_help_command_lists_available_commands(self): sender = '[email protected]' message = StubMessage(sender=sender, body='%s' % XmppHandler.HELP_CMD) self.handler.message_received(message=message) self.assertTrue(len(message.message_to_send) > 0) for command in XmppHandler.COMMAND_HELP_MSG_LIST: self.assertTrue(command in message.message_to_send, message.message_to_send) def test_alternative_help_command_lists_available_commands(self): sender = '[email protected]' message = StubMessage(sender=sender, body='%s' % XmppHandler.ALTERNATIVE_HELP_CMD) self.handler.message_received(message=message) self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % XmppHandler.ALTERNATIVE_HELP_CMD not in message.message_to_send) self.assertTrue(len(message.message_to_send) > 0) for command in XmppHandler.COMMAND_HELP_MSG_LIST: self.assertTrue(command in message.message_to_send, message.message_to_send) def test_search_command_succeeds_for_single_token(self): arg = 'onewordsearchterm' message = StubMessage(body='%s %s ' % (XmppHandler.SEARCH_CMD,arg)) self.handler.message_received(message=message) self.assertTrue(len(message.message_to_send) > 0, message) class XmppHandlerHttpTest(FunctionalTestCase, unittest.TestCase): APPLICATION = main.application def test_help_command_can_be_triggered_via_http(self): # Help command was chosen as it's idempotent and has no side-effects data = {'from' : settings.APP_NAME + '@appspot.com', 'to' : settings.APP_NAME + '@appspot.com', 'body' : 'help'} response = self.post('/_ah/xmpp/message/chat/', data=data) self.assertOK(response) def test_list_command_can_be_triggered_via_http(self): # List command was chosen as it's idempotent and has no side-effects data = {'from' : settings.APP_NAME + '@appspot.com', 'to' : settings.APP_NAME + '@appspot.com', 'body' : 'list'} response = self.post('/_ah/xmpp/message/chat/', data=data) self.assertOK(response) def test_search_command_can_be_triggered_via_http(self): data = {'from' : settings.APP_NAME + '@appspot.com', 'to' : settings.APP_NAME + '@appspot.com', 'body' : 'search somesearchterm'} response = self.post('/_ah/xmpp/message/chat/', data=data) self.assertOK(response) def test_invalid_http_request_triggers_error(self): response = self.post('/_ah/xmpp/message/chat/', data={}, expect_errors=True) self.assertEquals('400 Bad Request', response.status) diff --git a/oauth_handlers.py b/oauth_handlers.py index 51811ab..586f28c 100644 --- a/oauth_handlers.py +++ b/oauth_handlers.py @@ -1,150 +1,150 @@ # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from google.appengine.api import users from google.appengine.api import xmpp from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import login_required import buzz_gae_client import logging import os import settings import simple_buzz_wrapper class UserToken(db.Model): # The user_id is the key_name so we don't have to make it an explicit property request_token_string = db.StringProperty() access_token_string = db.StringProperty() email_address = db.StringProperty() def get_request_token(self): "Returns request token as a dictionary of tokens including oauth_token, oauth_token_secret and oauth_callback_confirmed." return eval(self.request_token_string) def set_access_token(self, access_token): access_token_string = repr(access_token) self.access_token_string = access_token_string def get_access_token(self): "Returns access token as a dictionary of tokens including consumer_key, consumer_secret, oauth_token and oauth_token_secret" return eval(self.access_token_string) @staticmethod def create_user_token(request_token): user = users.get_current_user() user_id = user.user_id() request_token_string = repr(request_token) # TODO(ade) Support users who sign in to AppEngine with a federated identity aka OpenId - email = user.email() + email = user.email().lower() logging.info('Creating user token: key_name: %s request_token_string: %s email_address: %s' % ( user_id, request_token_string, email)) return UserToken(key_name=user_id, request_token_string=request_token_string, access_token_string='', email_address=email) @staticmethod def get_current_user_token(): user = users.get_current_user() user_token = UserToken.get_by_key_name(user.user_id()) return user_token @staticmethod def access_token_exists(): user = users.get_current_user() user_token = UserToken.get_by_key_name(user.user_id()) logging.info('user_token: %s' % user_token) return user_token and user_token.access_token_string @staticmethod def find_by_email_address(email_address): user_tokens = UserToken.gql('WHERE email_address = :1', email_address).fetch(1) if user_tokens: return user_tokens[0] # The result of the query is a list else: return None class DanceStartingHandler(webapp.RequestHandler): @login_required def get(self): logging.info('Request body %s' % self.request.body) user = users.get_current_user() logging.debug('Started OAuth dance for: %s' % user.email()) template_values = {"jabber_id": ("%[email protected]" % settings.APP_NAME)} if UserToken.access_token_exists(): template_values['access_token_exists'] = 'true' else: # Generate the request token client = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET) request_token = client.get_request_token(self.request.host_url + '/finish_dance') logging.info('Request token: %s' % request_token) # Create the request token and associate it with the current user user_token = UserToken.create_user_token(request_token) UserToken.put(user_token) authorisation_url = client.generate_authorisation_url(request_token) logging.info('Authorisation URL is: %s' % authorisation_url) template_values['destination'] = authorisation_url path = os.path.join(os.path.dirname(__file__), 'start_dance.html') self.response.out.write(template.render(path, template_values)) class TokenDeletionHandler(webapp.RequestHandler): def post(self): user_token = UserToken.get_current_user_token() UserToken.delete(user_token) self.redirect(settings.FRONT_PAGE_HANDLER_URL) class DanceFinishingHandler(webapp.RequestHandler): def get(self): logging.info("Request body %s" % self.request.body) user = users.get_current_user() logging.debug('Finished OAuth dance for: %s' % user.email()) oauth_verifier = self.request.get('oauth_verifier') client = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET) user_token = UserToken.get_current_user_token() request_token = user_token.get_request_token() access_token = client.upgrade_to_access_token(request_token, oauth_verifier) logging.info('SUCCESS: Received access token.') user_token.set_access_token(access_token) UserToken.put(user_token) logging.debug('Access token was: %s' % user_token.access_token_string) # Send an XMPP invitation logging.info('Sending invite to %s' % user_token.email_address) xmpp.send_invite(user_token.email_address) msg = 'Welcome to the BuzzChatBot: %s' % settings.APP_URL xmpp.send_message(user_token.email_address, msg) self.redirect(settings.PROFILE_HANDLER_URL) def make_wrapper(email_address): user_token = UserToken.find_by_email_address(email_address) if user_token: oauth_params_dict = user_token.get_access_token() return simple_buzz_wrapper.SimpleBuzzWrapper(api_key=settings.API_KEY, consumer_key=oauth_params_dict['consumer_key'], consumer_secret=oauth_params_dict['consumer_secret'], oauth_token=oauth_params_dict['oauth_token'], oauth_token_secret=oauth_params_dict['oauth_token_secret']) else: return simple_buzz_wrapper.SimpleBuzzWrapper(api_key=settings.API_KEY) \ No newline at end of file diff --git a/xmpp.py b/xmpp.py index f131bf1..472279b 100644 --- a/xmpp.py +++ b/xmpp.py @@ -1,431 +1,431 @@ # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from google.appengine.api import xmpp from google.appengine.ext import db from google.appengine.ext import webapp import logging import oauth_handlers import pprint import pshb import re import settings import simple_buzz_wrapper import urllib class Subscription(db.Model): url = db.StringProperty(required=True) search_term = db.StringProperty(required=True) subscriber = db.StringProperty() def id(self): return self.key().id() def __eq__(self, other): if not other: return False return self.id() == other.id() @staticmethod def exists(id): """Return True or False to indicate if a subscription with the given id exists""" if not id: return False return Subscription.get_by_id(int(id)) is not None class Tracker(object): def __init__(self, hub_subscriber=pshb.HubSubscriber()): self.hub_subscriber = hub_subscriber @staticmethod def is_blank(string): """ utility function for determining whether a string is blank (just whitespace) """ return (string is None) or (len(string) == 0) or string.isspace() @staticmethod def extract_number(id): """Convert an id to an integer and return None if the conversion fails.""" if id is None: return None try: id = int(id) except ValueError, e: return None return id def _valid_subscription(self, search_term): return not Tracker.is_blank(search_term) def _subscribe(self, message_sender, search_term): message_sender = extract_sender_email_address(message_sender) url = self._build_subscription_url(search_term) logging.info('Subscribing to: %s for user: %s' % (url, message_sender)) subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender) db.put(subscription) callback_url = self._build_callback_url(subscription) logging.info('Callback URL was: %s' % callback_url) self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url) return subscription def _build_callback_url(self, subscription): return "%s/posts?id=%s" % (settings.APP_URL, subscription.id()) def _build_subscription_url(self, search_term): search_term = urllib.quote(search_term) return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term def track(self, message_sender, search_term): if self._valid_subscription(search_term): return self._subscribe(message_sender, search_term) else: return None def untrack(self, message_sender, id): """ Given an id, untrack takes it and attempts to unsubscribe from the list of tracked items. TODO(julian): you should be able to untrack <term> directly. """ logging.info("Tracker.untrack: id is: '%s'" % id) id_as_int = Tracker.extract_number(id) if id_as_int == None: # TODO(ade) Do a subscription lookup by name here return None subscription = Subscription.get_by_id(id_as_int) if not subscription: return None logging.info('Subscripton: %s' % str(subscription)) if subscription.subscriber != extract_sender_email_address(message_sender): return None subscription.delete() callback_url = self._build_callback_url(subscription) logging.info('Callback URL was: %s' % callback_url) self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url) return subscription class MessageBuilder(object): def __init__(self): self.lines = [] def build_message(self): text = '' for index,line in enumerate(self.lines): text += line if (index+1) < len(self.lines): text += '\n' return text def add(self, line): self.lines.append(line) def build_message_from_post(self, post, search_term): return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url) class SlashlessCommandMessage(xmpp.Message): """ The default message format with GAE xmpp identifies the command as the first non whitespace word. The argument is whatever occurs after that. Design notes: it uses re for tokenization which is a step up from how Message works (that expects a single space character) """ def __init__(self, vars): xmpp.Message.__init__(self, vars) #TODO(julian) make arg and command protected. because __arg and __command are hidden as private #in xmpp.Message, we have to define our own separate instances of these variables #even though all we do is change the property accessors for them. # scm = slashless command message # luckily __arg and __command aren't used elsewhere in Message but # we can't guarantee this so it's a bit of a mess self.__scm_arg = None self.__scm_command = None self.__message_to_send = None # END TODO @staticmethod def extract_command_and_arg_from_string(string): # match any white space and then a word (cmd) # then any white space then everything after that (arg). command = None arg = None results = re.search(r"\s*(\S*)\s*(.*)", string) if results: command = results.group(1) arg = results.group(2) # we didn't find a command and an arg so maybe we'll just find the command # some commands may not have args else: results = re.search(r"\s*(\S*)\s*", string) if results: command = results.group(1) return (command,arg) def __ensure_command_and_args_extracted(self): """ Take the message and identify the command and argument if there is one. In the case of a SlashlessCommandMessage, there is always one -- the first word is the command. """ # cache the values. if not self.__scm_command: self.__scm_command,self.__scm_arg = SlashlessCommandMessage.extract_command_and_arg_from_string(self.body) logging.info("command = '%s', arg = '%s'" %(self.__scm_command,self.__scm_arg)) # These properties are redefined from that defined in xmpp.Message @property def command(self): self.__ensure_command_and_args_extracted() return self.__scm_command @property def arg(self): self.__ensure_command_and_args_extracted() return self.__scm_arg @property def message_to_send(self): """ TODO(julian) rename: this is actually response_message """ return self.__message_to_send def reply(self, message_to_send, raw_xml=False): logging.debug( "SlashlessCommandMessage.reply: message_to_send = %s" % message_to_send) xmpp.Message.reply(self, message_to_send, raw_xml=raw_xml) self.__message_to_send = message_to_send class XmppHandler(webapp.RequestHandler): ABOUT_CMD = 'about' HELP_CMD = 'help' ALTERNATIVE_HELP_CMD = '?' LIST_CMD = 'list' POST_CMD = 'post' TRACK_CMD = 'track' UNTRACK_CMD = 'untrack' SEARCH_CMD = 'search' PERMITTED_COMMANDS = [ABOUT_CMD,HELP_CMD,ALTERNATIVE_HELP_CMD,LIST_CMD,POST_CMD,TRACK_CMD,UNTRACK_CMD, SEARCH_CMD] COMMAND_HELP_MSG_LIST = [ '%s Prints out this message' % HELP_CMD, '%s Prints out this message' % ALTERNATIVE_HELP_CMD, '%s [search term] Starts tracking the given search term and returns the id for your subscription' % TRACK_CMD, '%s [id] Removes your subscription for that id' % UNTRACK_CMD, '%s Lists all search terms and ids currently being tracked by you' % LIST_CMD, '%s Tells you which instance of the Buzz Chat Bot you are using' % ABOUT_CMD, '%s [some message] Posts that message to Buzz' % POST_CMD, '%s [some search term] Searches for that search term on Buzz' ] TRACK_FAILED_MSG = 'Sorry there was a problem with that track command ' NOTHING_TO_TRACK_MSG = "To track a phrase on buzz, you need to enter the phrase :) Please type: track <your phrase to track>" UNKNOWN_COMMAND_MSG = "Sorry, '%s' was not understood. Here are a list of the things you can do:" SUBSCRIPTION_SUCCESS_MSG = 'Tracking: %s with id: %s' LIST_NOT_TRACKING_ANYTHING_MSG = 'You are not tracking anything. To track when a word or phrase appears in Buzz, enter: track <thing of interest>' def __init__(self, hub_subscriber=pshb.HubSubscriber()): self.tracker = Tracker(hub_subscriber=hub_subscriber) def unhandled_command(self, message): """ User entered a command that is not recognised. Tell them this and show help""" self.help_command(message, XmppHandler.UNKNOWN_COMMAND_MSG % message.command ) def _make_wrapper(self, email_address): return oauth_handlers.make_wrapper(email_address) def message_received(self, message): """ Take the message we've received and dispatch it to the appropriate command handler using introspection. E.g. if the command is 'track' it will map to track_command. Args: message: Message: The message that was sent by the user. """ logging.info('Command was: %s' % message.command) command = self._get_canonical_command(message) self.buzz_wrapper = self._make_wrapper(extract_sender_email_address(message.sender)) if command and command in XmppHandler.PERMITTED_COMMANDS: handler_name = '%s_command' % command handler = getattr(self, handler_name, None) if handler: handler(message) return else: logging.info('No handler available for command: %s' % command) self.unhandled_command(message) def _get_canonical_command(self, message): command = message.command.lower() # The old-style / prefixed commands are honoured as if they were slashless commands. This provides backwards # compatibility for early adopters and people who are used to IRC syntax. if command.startswith('/'): command = command[1:] # Handle aliases for commands if command == XmppHandler.ALTERNATIVE_HELP_CMD: command = XmppHandler.HELP_CMD return command def post(self): """ Redefines post to create a message from our new SlashlessCommandMessage. TODO(julian) xmpp_handlers: redefine the BaseHandler to have a function createMessage which can be overridden this will avoid the code duplicated below """ logging.info("Received chat msg, raw post = '%s'" % self.request.POST) try: # CHANGE this is the only bit that has changed from xmpp_handlers.Message self.xmpp_message = SlashlessCommandMessage(self.request.POST) # END CHANGE except xmpp.InvalidMessageError, e: logging.error("Invalid XMPP request: Missing required field: %s", e[0]) self.error(400) return self.message_received(self.xmpp_message) def handle_exception(self, exception, debug_mode): logging.error('handle_exception: calling webapp.RequestHandler superclass') # All code that logs the content of the error uses pprint.pformat() because in situations # where the message contains non-ASCII characters the use of str() was causing # an exception in the logging library which would hide the original exception logging.error('Exception: %s' % pprint.pformat(exception)) if self.xmpp_message: self.xmpp_message.reply('Oops. Something went wrong. Sorry about that') logging.error('User visible oops for message: %s' % pprint.pformat(self.xmpp_message.body)) def help_command(self, message=None, prompt='We all need a little help sometimes' ): """ Print out the help command. Optionally accepts a message builder so help can be printed out if the user looks like they're having trouble """ logging.info('Received message from: %s' % message.sender) lines = [prompt] lines.extend(self.COMMAND_HELP_MSG_LIST) message_builder = MessageBuilder() for line in lines: message_builder.add(line) reply(message_builder, message) def track_command(self, message=None): """ Start tracking a phrase against the Buzz API. message must be a valid xmpp.Message or subclass and cannot be null. """ logging.debug('Received message from: %s' % message.sender) subscription = None message_builder = MessageBuilder() if message.arg == '': message_builder.add( XmppHandler.NOTHING_TO_TRACK_MSG ) else: logging.debug( "track_command: calling tracker.track with term '%s'" % message.arg ) subscription = self.tracker.track(message.sender, message.arg) if subscription: message_builder.add( XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (subscription.search_term, subscription.id())) else: message_builder.add('%s <%s>' % (XmppHandler.TRACK_FAILED_MSG, message.body)) reply(message_builder, message) logging.debug( "message.message_to_send = '%s'" % message.message_to_send ) return subscription def untrack_command(self, message=None): logging.info('Received message from: %s' % message.sender) subscription = self.tracker.untrack(message.sender, message.arg) message_builder = MessageBuilder() if subscription: message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id())) else: message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: %s [id]' % XmppHandler.UNTRACK_CMD) reply(message_builder, message) def list_command(self, message=None): logging.info('Received message from: %s' % message.sender) message_builder = MessageBuilder() sender = extract_sender_email_address(message.sender) logging.info('Sender: %s' % sender) subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender) if subscriptions_query.count() > 0: for subscription in subscriptions_query: message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id())) else: message_builder.add(XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG) reply(message_builder, message) def about_command(self, message): logging.info('Received message from: %s' % message.sender) message_builder = MessageBuilder() about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: %s' % (settings.APP_NAME, settings.APP_URL) message_builder.add(about_message) reply(message_builder, message) def post_command(self, message): logging.info('Received message from: %s' % message.sender) message_builder = MessageBuilder() sender = extract_sender_email_address(message.sender) user_token = oauth_handlers.UserToken.find_by_email_address(sender) if not user_token: message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL)) logging.debug('%s has not given access to their Google Buzz account but is attempting to post anyway' % sender) elif not user_token.access_token_string: logging.debug('%s did not complete the process for giving access to their Google Buzz account. Deleting their incomplete token: %s' % (sender, str(user_token))) # User didn't finish the OAuth dance so we make them start again user_token.delete() message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL)) logging.debug('%s did not complete the process for giving access to their Google Buzz account. Deleting their incomplete token.' % sender) else: url = self.buzz_wrapper.post(sender, message.arg) message_builder.add('Posted: %s' % url) reply(message_builder, message) def search_command(self, message): logging.info('Received message from: %s' % message.sender) message_builder = MessageBuilder() sender = extract_sender_email_address(message.sender) logging.info('Sender: %s' % sender) message_builder.add('Search results for %s:' % message.arg) results = self.buzz_wrapper.search(message.arg) for index, result in enumerate(results): title = result['title'] permalink = result['links']['alternate'][0]['href'] line = '%s- %s : %s' % (index+1, title, permalink) message_builder.add(line) reply(message_builder, message) def extract_sender_email_address(message_sender): - return message_sender.split('/')[0] + return message_sender.split('/')[0].lower() def reply(message_builder, message): message_to_send = message_builder.build_message() logging.info('Message that will be sent: %s' % message_to_send) message.reply(message_to_send, raw_xml=False) def send_posts(posts, subscriber, search_term): message_builder = MessageBuilder() for post in posts: xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False) \ No newline at end of file
adewale/Buzz-Chat-Bot
de5dfd03448e8e94346b8211031fd376279ff388
Redirect un-authorised users to the homepage
diff --git a/main.py b/main.py index c422de6..991f89c 100644 --- a/main.py +++ b/main.py @@ -1,125 +1,130 @@ # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import login_required from google.appengine.ext.webapp.util import run_wsgi_app import logging import oauth_handlers import os import settings import xmpp import pshb import simple_buzz_wrapper class ProfileViewingHandler(webapp.RequestHandler): @login_required def get(self): - user_token = oauth_handlers.UserToken.get_current_user_token() + + # Users who don't have tokens should get sent to the front page + if not oauth_handlers.UserToken.access_token_exists(): + self.redirect('/') + return + + user_token = oauth_handlers.UserToken.get_current_user_token() buzz_wrapper = oauth_handlers.make_wrapper(user_token.email_address) user_profile_data = buzz_wrapper.get_profile() template_values = {'user_profile_data': user_profile_data, 'access_token': user_token.access_token_string} path = os.path.join(os.path.dirname(__file__), 'profile.html') self.response.out.write(template.render(path, template_values)) class FrontPageHandler(webapp.RequestHandler): def get(self): template_values = {'commands' : xmpp.XmppHandler.COMMAND_HELP_MSG_LIST, 'help_command' : xmpp.XmppHandler.HELP_CMD, 'jabber_id' : '%[email protected]' % settings.APP_NAME, 'admin_url' : settings.ADMIN_PROFILE_URL} path = os.path.join(os.path.dirname(__file__), 'front_page.html') self.response.out.write(template.render(path, template_values)) class PostsHandler(webapp.RequestHandler): def _get_subscription(self): logging.info("Headers were: %s" % str(self.request.headers)) logging.info('Request: %s' % str(self.request)) id = self.request.get('id') subscription = xmpp.Subscription.get_by_id(int(id)) return subscription def get(self): """Show all the resources in this collection""" logging.info("Headers were: %s" % str(self.request.headers)) logging.info('Request: %s' % str(self.request)) - logging.debug("New content: %s" % self.request.body) id = self.request.get('id') logging.debug("Request id = '%s'", id) # If this is a hub challenge if self.request.get('hub.challenge'): # If this subscription exists mode = self.request.get('hub.mode') topic = self.request.get('hub.topic') if mode == "subscribe" and xmpp.Subscription.get_by_id(int(id)): self.response.out.write(self.request.get('hub.challenge')) logging.info("Successfully accepted %s challenge for feed: %s" % (mode, topic)) elif mode == "unsubscribe" and not xmpp.Subscription.get_by_id(int(id)): self.response.out.write(self.request.get('hub.challenge')) logging.info("Successfully accepted %s challenge for feed: %s" % (mode, topic)) else: self.response.set_status(404) self.response.out.write("Challenge failed") logging.info("Challenge failed for feed: %s" % topic) # Once a challenge has been issued there's no point in returning anything other than challenge passed or failed return def post(self): """Create a new resource in this collection""" logging.info("Headers were: %s" % str(self.request.headers)) id = self.request.get('id') logging.debug("Request id = '%s'", id) subscription = xmpp.Subscription.get_by_id(int(id)) if not subscription: self.response.set_status(404) self.response.out.write("No such subscription") logging.warning('No subscription for %s' % id) return subscriber = subscription.subscriber search_term = subscription.search_term parser = pshb.ContentParser(self.request.body, settings.DEFAULT_HUB, settings.ALWAYS_USE_DEFAULT_HUB) url = parser.extractFeedUrl() if not parser.dataValid(): parser.logErrors() self.response.out.write("Bad entries: %s" % parser.data) return else: posts = parser.extractPosts() logging.info("Successfully received %s posts for subscription: %s" % (len(posts), url)) xmpp.send_posts(posts, subscriber, search_term) self.response.set_status(200) application = webapp.WSGIApplication([ (settings.FRONT_PAGE_HANDLER_URL, FrontPageHandler), (settings.PROFILE_HANDLER_URL, ProfileViewingHandler), ('/start_dance', oauth_handlers.DanceStartingHandler), ('/finish_dance', oauth_handlers.DanceFinishingHandler), ('/delete_tokens', oauth_handlers.TokenDeletionHandler), ('/posts', PostsHandler), ('/_ah/xmpp/message/chat/', xmpp.XmppHandler), ], debug=True) def main(): run_wsgi_app(application) if __name__ == '__main__': main()
adewale/Buzz-Chat-Bot
3782eade9e9f8c3837b44f09e11480a948845d8d
Tracked the problem to a situation where the format of JID in Adium isn't a valid email address so the lookup for the UserToken was failing and the wrapper was falling back to an ApiClient that didn't have an access token. This meant that actions like posting, which require authorisation, were failing based on the format of the sender's JID.
diff --git a/functional_tests.py b/functional_tests.py index 4a13c64..bd76c08 100644 --- a/functional_tests.py +++ b/functional_tests.py @@ -1,380 +1,394 @@ # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import main import unittest from gaetestbed import FunctionalTestCase from stubs import StubMessage, StubSimpleBuzzWrapper from tracker_tests import StubHubSubscriber -from xmpp import Tracker, XmppHandler +from xmpp import Tracker, XmppHandler, extract_sender_email_address import oauth_handlers import settings class FrontPageHandlerFunctionalTest(FunctionalTestCase, unittest.TestCase): APPLICATION = main.application def test_front_page_can_be_viewed_without_being_logged_in(self): response = self.get(settings.FRONT_PAGE_HANDLER_URL) self.assertOK(response) response.mustcontain("<title>Buzz Chat Bot") response.mustcontain(settings.APP_NAME) def test_admin_profile_link_is_on_front_page(self): response = self.get(settings.FRONT_PAGE_HANDLER_URL) self.assertOK(response) response.mustcontain('href="%s"' % settings.ADMIN_PROFILE_URL) class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase): def _setup_subscription(self, sender='[email protected]',search_term='somestring'): search_term = search_term body = '%s %s' % (XmppHandler.TRACK_CMD,search_term) hub_subscriber = StubHubSubscriber() tracker = Tracker(hub_subscriber=hub_subscriber) subscription = tracker.track(sender, body) return subscription class PostsHandlerTest(BuzzChatBotFunctionalTestCase): APPLICATION = main.application def test_can_validate_hub_challenge_for_subscribe(self): subscription = self._setup_subscription() challenge = 'somechallengetoken' topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring' response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id())) self.assertOK(response) response.mustcontain(challenge) def test_can_validate_hub_challenge_for_unsubscribe(self): subscription = self._setup_subscription() subscription.delete() challenge = 'somechallengetoken' topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring' response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id())) self.assertOK(response) response.mustcontain(challenge) class StubXmppHandler(XmppHandler): def _make_wrapper(self, email_address): + self.email_address = email_address return StubSimpleBuzzWrapper() class XmppHandlerTest(BuzzChatBotFunctionalTestCase): def __init__(self, methodName='runTest'): BuzzChatBotFunctionalTestCase.__init__(self, methodName) self.stub_hub_subscriber = StubHubSubscriber() self.handler = StubXmppHandler(hub_subscriber=self.stub_hub_subscriber) def test_track_command_succeeds_for_varying_combinations_of_whitespace(self): arg = 'Some day my prints will come' message = StubMessage( body='%s %s ' % (XmppHandler.TRACK_CMD,arg)) # We call the method directly here because we actually care about the object that is returned subscription = self.handler.track_command(message=message) self.assertEqual(message.message_to_send, XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (message.arg,subscription.id())) def test_invalid_symbol_command_shows_correct_error(self): command = '~' message = StubMessage(body=command) self.handler.message_received(message) self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % command in message.message_to_send, message.message_to_send) def test_unhandled_command_shows_correct_error(self): command = 'wibble' message = StubMessage(body=command) self.handler.message_received(message) self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % command in message.message_to_send, message.message_to_send) def test_track_command_fails_for_missing_term(self): message = StubMessage(body='%s ' % XmppHandler.TRACK_CMD) self.handler.message_received(message=message) self.assertTrue(XmppHandler.NOTHING_TO_TRACK_MSG in message.message_to_send, message.message_to_send) def test_untrack_command_fails_for_missing_subscription_value(self): message = StubMessage(body='%s 777' % XmppHandler.UNTRACK_CMD) self.handler.message_received(message=message) self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send) def test_untrack_command_fails_for_missing_subscription_argument(self): self._setup_subscription() message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD) self.handler.message_received(message=message) self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send) def test_untrack_command_fails_for_wrong_subscription_id(self): subscription = self._setup_subscription() id = subscription.id() + 1 message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD,id)) self.handler.message_received(message=message) self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send) def test_untrack_command_succeeds_for_valid_subscription_id(self): subscription = self._setup_subscription() id = subscription.id() message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD, id)) self.handler.message_received(message=message) self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send) def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self): subscription = self._setup_subscription() id = subscription.id() message = StubMessage(sender='[email protected]', body='%s %s' % (XmppHandler.UNTRACK_CMD,id)) self.handler.message_received(message=message) self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send) def test_untrack_command_fails_for_malformed_subscription_id(self): message = StubMessage(body='%s jaiku' % XmppHandler.UNTRACK_CMD) self.handler.message_received(message=message) self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send) def test_untrack_command_fails_for_empty_subscription_id(self): message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD) self.handler.message_received(message=message) self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send) def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self): sender1 = '[email protected]' subscription1 = self._setup_subscription(sender=sender1, search_term='searchA') sender2 = '[email protected]' subscription2 = self._setup_subscription(sender=sender2, search_term='searchB') for people in [(sender1, subscription1), (sender2, subscription2)]: sender = people[0] message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD) self.handler.message_received(message=message) subscription = people[1] self.assertTrue(str(subscription.id()) in message.message_to_send) expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id()) self.assertTrue(expected_item in message.message_to_send, message.message_to_send) def test_list_command_can_show_exactly_one_subscription(self): sender = '[email protected]' subscription = self._setup_subscription(sender=sender, search_term='searchA') message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD) self.handler.message_received(message=message) expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id()) self.assertEquals(expected_item, message.message_to_send) def test_list_command_can_handle_empty_set_of_search_terms(self): sender = '[email protected]' message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD) self.handler.message_received(message=message) expected_item = XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG self.assertTrue(len(message.message_to_send) > 0) self.assertTrue(expected_item in message.message_to_send, message.message_to_send) def test_about_command_says_what_bot_is_running(self): sender = '[email protected]' message = StubMessage(sender=sender, body='%s' % XmppHandler.ABOUT_CMD) self.handler.message_received(message=message) expected_item = 'Welcome to %[email protected]. A bot for Google Buzz' % settings.APP_NAME self.assertTrue(expected_item in message.message_to_send, message.message_to_send) def test_post_command_warns_users_with_no_oauth_token(self): sender = '[email protected]' message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD) self.handler.message_received(message=message) expected_item = 'You (%s) have not given access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL) self.assertTrue(expected_item in message.message_to_send, message.message_to_send) def test_post_command_warns_users_with_no_access_token(self): sender = '[email protected]' user_token = oauth_handlers.UserToken(email_address=sender) user_token.put() message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD) self.handler.message_received(message=message) expected_item = 'You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL) self.assertEquals(expected_item, message.message_to_send) self.assertEquals(None, oauth_handlers.UserToken.find_by_email_address(sender)) def test_post_command_posts_message_for_user_with_oauth_token(self): sender = '[email protected]' user_token = oauth_handlers.UserToken(email_address=sender) user_token.access_token_string = 'some thing that looks like an access token from a distance' user_token.put() message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD) self.handler.message_received(message=message) expected_item = 'Posted: %s' % self.handler.buzz_wrapper.url self.assertEquals(expected_item, message.message_to_send) + def test_post_command_posts_message_for_for_correct_sender(self): + # Using Adium format for message sender id + sender = '[email protected]/Adium457EE950' + email_address = extract_sender_email_address(sender) + user_token = oauth_handlers.UserToken(email_address=email_address) + user_token.access_token_string = 'some thing that looks like an access token from a distance' + user_token.put() + message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD) + + self.handler.message_received(message=message) + + self.assertEquals(email_address, self.handler.email_address) + def test_post_command_strips_command_from_posted_message(self): sender = '[email protected]' user_token = oauth_handlers.UserToken(email_address=sender) user_token.access_token_string = 'some thing that looks like an access token from a distance' user_token.put() message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD) self.handler.message_received(message=message) expected_item = 'some message' self.assertEquals(expected_item, self.handler.buzz_wrapper.message) def test_slash_post_command_strips_command_from_posted_message(self): sender = '[email protected]' user_token = oauth_handlers.UserToken(email_address=sender) user_token.access_token_string = 'some thing that looks like an access token from a distance' user_token.put() message = StubMessage(sender=sender, body='/%s some message' % XmppHandler.POST_CMD) self.handler.message_received(message=message) expected_item = 'some message' self.assertEquals(expected_item, self.handler.buzz_wrapper.message) def test_slash_post_gets_treated_as_post_command(self): sender = '[email protected]' user_token = oauth_handlers.UserToken(email_address=sender) user_token.access_token_string = 'some thing that looks like an access token from a distance' user_token.put() message = StubMessage(sender=sender, body='/%s some message' % XmppHandler.POST_CMD) self.handler.message_received(message=message) expected_item = 'Posted: %s' % self.handler.buzz_wrapper.url self.assertEquals(expected_item, message.message_to_send) def test_uppercase_post_gets_treated_as_post_command(self): sender = '[email protected]' user_token = oauth_handlers.UserToken(email_address=sender) user_token.access_token_string = 'some thing that looks like an access token from a distance' user_token.put() message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD.upper()) self.handler.message_received(message=message) expected_item = 'Posted: %s' % self.handler.buzz_wrapper.url self.assertEquals(expected_item, message.message_to_send) def test_slash_uppercase_post_gets_treated_as_post_command(self): sender = '[email protected]' user_token = oauth_handlers.UserToken(email_address=sender) user_token.access_token_string = 'some thing that looks like an access token from a distance' user_token.put() message = StubMessage(sender=sender, body='/%s some message' % XmppHandler.POST_CMD.upper()) self.handler.message_received(message=message) expected_item = 'Posted: %s' % self.handler.buzz_wrapper.url self.assertEquals(expected_item, message.message_to_send) def test_help_command_lists_available_commands(self): sender = '[email protected]' message = StubMessage(sender=sender, body='%s' % XmppHandler.HELP_CMD) self.handler.message_received(message=message) self.assertTrue(len(message.message_to_send) > 0) for command in XmppHandler.COMMAND_HELP_MSG_LIST: self.assertTrue(command in message.message_to_send, message.message_to_send) def test_alternative_help_command_lists_available_commands(self): sender = '[email protected]' message = StubMessage(sender=sender, body='%s' % XmppHandler.ALTERNATIVE_HELP_CMD) self.handler.message_received(message=message) self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % XmppHandler.ALTERNATIVE_HELP_CMD not in message.message_to_send) self.assertTrue(len(message.message_to_send) > 0) for command in XmppHandler.COMMAND_HELP_MSG_LIST: self.assertTrue(command in message.message_to_send, message.message_to_send) def test_search_command_succeeds_for_single_token(self): arg = 'onewordsearchterm' message = StubMessage(body='%s %s ' % (XmppHandler.SEARCH_CMD,arg)) self.handler.message_received(message=message) self.assertTrue(len(message.message_to_send) > 0, message) class XmppHandlerHttpTest(FunctionalTestCase, unittest.TestCase): APPLICATION = main.application def test_help_command_can_be_triggered_via_http(self): # Help command was chosen as it's idempotent and has no side-effects data = {'from' : settings.APP_NAME + '@appspot.com', 'to' : settings.APP_NAME + '@appspot.com', 'body' : 'help'} response = self.post('/_ah/xmpp/message/chat/', data=data) self.assertOK(response) def test_list_command_can_be_triggered_via_http(self): # List command was chosen as it's idempotent and has no side-effects data = {'from' : settings.APP_NAME + '@appspot.com', 'to' : settings.APP_NAME + '@appspot.com', 'body' : 'list'} response = self.post('/_ah/xmpp/message/chat/', data=data) self.assertOK(response) def test_search_command_can_be_triggered_via_http(self): data = {'from' : settings.APP_NAME + '@appspot.com', 'to' : settings.APP_NAME + '@appspot.com', 'body' : 'search somesearchterm'} response = self.post('/_ah/xmpp/message/chat/', data=data) self.assertOK(response) def test_invalid_http_request_triggers_error(self): response = self.post('/_ah/xmpp/message/chat/', data={}, expect_errors=True) self.assertEquals('400 Bad Request', response.status) diff --git a/simple_buzz_wrapper.py b/simple_buzz_wrapper.py index 619815b..91c0cd0 100644 --- a/simple_buzz_wrapper.py +++ b/simple_buzz_wrapper.py @@ -1,69 +1,71 @@ # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import buzz_gae_client import logging class SimpleBuzzWrapper(object): "Simple client that exposes the bare minimum set of common Buzz operations" def __init__(self, api_key=None, consumer_key='anonymous', consumer_secret='anonymous', oauth_token=None, oauth_token_secret=None): self.builder = buzz_gae_client.BuzzGaeClient(consumer_key, consumer_secret, api_key=api_key) if oauth_token and oauth_token_secret: + logging.info('Using api_client with authorisation') oauth_params_dict = {} oauth_params_dict['consumer_key'] = consumer_key oauth_params_dict['consumer_secret'] = consumer_secret oauth_params_dict['oauth_token'] = oauth_token oauth_params_dict['oauth_token_secret'] = oauth_token_secret self.api_client = self.builder.build_api_client(oauth_params=oauth_params_dict) else: + logging.info('Using api_client that doesn\'t have authorisation') self.api_client = self.builder.build_api_client() def search(self, query, user_token=None, max_results=10): if query is None or query.strip() is '': return None json = self.api_client.activities().search(q=query, max_results=max_results).execute() if json.has_key('items'): return json['items'] return [] def post(self, sender, message_body): if message_body is None or message_body.strip() is '': return None #TODO(ade) What happens with users who have hidden their email address? # Maybe we should switch to @me so it won't matter? user_id = sender.split('@')[0] activities = self.api_client.activities() logging.info('Retrieved activities for: %s' % user_id) activity = activities.insert(userId=user_id, body={ 'data' : { 'title': message_body, 'object': { 'content': message_body, 'type': 'note'} } } ).execute() url = activity['links']['alternate'][0]['href'] logging.info('Just created: %s' % url) return url def get_profile(self, user_id='@me'): user_profile_data = self.api_client.people().get(userId=user_id).execute() return user_profile_data diff --git a/xmpp.py b/xmpp.py index 9eb6107..f131bf1 100644 --- a/xmpp.py +++ b/xmpp.py @@ -1,431 +1,431 @@ # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from google.appengine.api import xmpp from google.appengine.ext import db from google.appengine.ext import webapp import logging import oauth_handlers import pprint import pshb import re import settings import simple_buzz_wrapper import urllib class Subscription(db.Model): url = db.StringProperty(required=True) search_term = db.StringProperty(required=True) subscriber = db.StringProperty() def id(self): return self.key().id() def __eq__(self, other): if not other: return False return self.id() == other.id() @staticmethod def exists(id): """Return True or False to indicate if a subscription with the given id exists""" if not id: return False return Subscription.get_by_id(int(id)) is not None class Tracker(object): def __init__(self, hub_subscriber=pshb.HubSubscriber()): self.hub_subscriber = hub_subscriber @staticmethod def is_blank(string): """ utility function for determining whether a string is blank (just whitespace) """ return (string is None) or (len(string) == 0) or string.isspace() @staticmethod def extract_number(id): """Convert an id to an integer and return None if the conversion fails.""" if id is None: return None try: id = int(id) except ValueError, e: return None return id def _valid_subscription(self, search_term): return not Tracker.is_blank(search_term) def _subscribe(self, message_sender, search_term): message_sender = extract_sender_email_address(message_sender) url = self._build_subscription_url(search_term) logging.info('Subscribing to: %s for user: %s' % (url, message_sender)) subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender) db.put(subscription) callback_url = self._build_callback_url(subscription) logging.info('Callback URL was: %s' % callback_url) self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url) return subscription def _build_callback_url(self, subscription): return "%s/posts?id=%s" % (settings.APP_URL, subscription.id()) def _build_subscription_url(self, search_term): search_term = urllib.quote(search_term) return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term def track(self, message_sender, search_term): if self._valid_subscription(search_term): return self._subscribe(message_sender, search_term) else: return None def untrack(self, message_sender, id): """ Given an id, untrack takes it and attempts to unsubscribe from the list of tracked items. TODO(julian): you should be able to untrack <term> directly. """ logging.info("Tracker.untrack: id is: '%s'" % id) id_as_int = Tracker.extract_number(id) if id_as_int == None: # TODO(ade) Do a subscription lookup by name here return None subscription = Subscription.get_by_id(id_as_int) if not subscription: return None logging.info('Subscripton: %s' % str(subscription)) if subscription.subscriber != extract_sender_email_address(message_sender): return None subscription.delete() callback_url = self._build_callback_url(subscription) logging.info('Callback URL was: %s' % callback_url) self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url) return subscription class MessageBuilder(object): def __init__(self): self.lines = [] def build_message(self): text = '' for index,line in enumerate(self.lines): text += line if (index+1) < len(self.lines): text += '\n' return text def add(self, line): self.lines.append(line) def build_message_from_post(self, post, search_term): return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url) class SlashlessCommandMessage(xmpp.Message): """ The default message format with GAE xmpp identifies the command as the first non whitespace word. The argument is whatever occurs after that. Design notes: it uses re for tokenization which is a step up from how Message works (that expects a single space character) """ def __init__(self, vars): xmpp.Message.__init__(self, vars) #TODO(julian) make arg and command protected. because __arg and __command are hidden as private #in xmpp.Message, we have to define our own separate instances of these variables #even though all we do is change the property accessors for them. # scm = slashless command message # luckily __arg and __command aren't used elsewhere in Message but # we can't guarantee this so it's a bit of a mess self.__scm_arg = None self.__scm_command = None self.__message_to_send = None # END TODO @staticmethod def extract_command_and_arg_from_string(string): # match any white space and then a word (cmd) # then any white space then everything after that (arg). command = None arg = None results = re.search(r"\s*(\S*)\s*(.*)", string) if results: command = results.group(1) arg = results.group(2) # we didn't find a command and an arg so maybe we'll just find the command # some commands may not have args else: results = re.search(r"\s*(\S*)\s*", string) if results: command = results.group(1) return (command,arg) def __ensure_command_and_args_extracted(self): """ Take the message and identify the command and argument if there is one. In the case of a SlashlessCommandMessage, there is always one -- the first word is the command. """ # cache the values. if not self.__scm_command: self.__scm_command,self.__scm_arg = SlashlessCommandMessage.extract_command_and_arg_from_string(self.body) logging.info("command = '%s', arg = '%s'" %(self.__scm_command,self.__scm_arg)) # These properties are redefined from that defined in xmpp.Message @property def command(self): self.__ensure_command_and_args_extracted() return self.__scm_command @property def arg(self): self.__ensure_command_and_args_extracted() return self.__scm_arg @property def message_to_send(self): """ TODO(julian) rename: this is actually response_message """ return self.__message_to_send def reply(self, message_to_send, raw_xml=False): logging.debug( "SlashlessCommandMessage.reply: message_to_send = %s" % message_to_send) xmpp.Message.reply(self, message_to_send, raw_xml=raw_xml) self.__message_to_send = message_to_send class XmppHandler(webapp.RequestHandler): ABOUT_CMD = 'about' HELP_CMD = 'help' ALTERNATIVE_HELP_CMD = '?' LIST_CMD = 'list' POST_CMD = 'post' TRACK_CMD = 'track' UNTRACK_CMD = 'untrack' SEARCH_CMD = 'search' PERMITTED_COMMANDS = [ABOUT_CMD,HELP_CMD,ALTERNATIVE_HELP_CMD,LIST_CMD,POST_CMD,TRACK_CMD,UNTRACK_CMD, SEARCH_CMD] COMMAND_HELP_MSG_LIST = [ '%s Prints out this message' % HELP_CMD, '%s Prints out this message' % ALTERNATIVE_HELP_CMD, '%s [search term] Starts tracking the given search term and returns the id for your subscription' % TRACK_CMD, '%s [id] Removes your subscription for that id' % UNTRACK_CMD, '%s Lists all search terms and ids currently being tracked by you' % LIST_CMD, '%s Tells you which instance of the Buzz Chat Bot you are using' % ABOUT_CMD, '%s [some message] Posts that message to Buzz' % POST_CMD, '%s [some search term] Searches for that search term on Buzz' ] TRACK_FAILED_MSG = 'Sorry there was a problem with that track command ' NOTHING_TO_TRACK_MSG = "To track a phrase on buzz, you need to enter the phrase :) Please type: track <your phrase to track>" UNKNOWN_COMMAND_MSG = "Sorry, '%s' was not understood. Here are a list of the things you can do:" SUBSCRIPTION_SUCCESS_MSG = 'Tracking: %s with id: %s' LIST_NOT_TRACKING_ANYTHING_MSG = 'You are not tracking anything. To track when a word or phrase appears in Buzz, enter: track <thing of interest>' def __init__(self, hub_subscriber=pshb.HubSubscriber()): self.tracker = Tracker(hub_subscriber=hub_subscriber) def unhandled_command(self, message): """ User entered a command that is not recognised. Tell them this and show help""" self.help_command(message, XmppHandler.UNKNOWN_COMMAND_MSG % message.command ) def _make_wrapper(self, email_address): return oauth_handlers.make_wrapper(email_address) def message_received(self, message): """ Take the message we've received and dispatch it to the appropriate command handler using introspection. E.g. if the command is 'track' it will map to track_command. Args: message: Message: The message that was sent by the user. """ logging.info('Command was: %s' % message.command) command = self._get_canonical_command(message) - self.buzz_wrapper = self._make_wrapper(message.sender) + self.buzz_wrapper = self._make_wrapper(extract_sender_email_address(message.sender)) if command and command in XmppHandler.PERMITTED_COMMANDS: handler_name = '%s_command' % command handler = getattr(self, handler_name, None) if handler: handler(message) return else: logging.info('No handler available for command: %s' % command) self.unhandled_command(message) def _get_canonical_command(self, message): command = message.command.lower() # The old-style / prefixed commands are honoured as if they were slashless commands. This provides backwards # compatibility for early adopters and people who are used to IRC syntax. if command.startswith('/'): command = command[1:] # Handle aliases for commands if command == XmppHandler.ALTERNATIVE_HELP_CMD: command = XmppHandler.HELP_CMD return command def post(self): """ Redefines post to create a message from our new SlashlessCommandMessage. TODO(julian) xmpp_handlers: redefine the BaseHandler to have a function createMessage which can be overridden this will avoid the code duplicated below """ logging.info("Received chat msg, raw post = '%s'" % self.request.POST) try: # CHANGE this is the only bit that has changed from xmpp_handlers.Message self.xmpp_message = SlashlessCommandMessage(self.request.POST) # END CHANGE except xmpp.InvalidMessageError, e: logging.error("Invalid XMPP request: Missing required field: %s", e[0]) self.error(400) return self.message_received(self.xmpp_message) def handle_exception(self, exception, debug_mode): logging.error('handle_exception: calling webapp.RequestHandler superclass') - # All code that logs the content of the error uses pformat because in situations + # All code that logs the content of the error uses pprint.pformat() because in situations # where the message contains non-ASCII characters the use of str() was causing # an exception in the logging library which would hide the original exception logging.error('Exception: %s' % pprint.pformat(exception)) if self.xmpp_message: self.xmpp_message.reply('Oops. Something went wrong. Sorry about that') logging.error('User visible oops for message: %s' % pprint.pformat(self.xmpp_message.body)) def help_command(self, message=None, prompt='We all need a little help sometimes' ): """ Print out the help command. Optionally accepts a message builder so help can be printed out if the user looks like they're having trouble """ logging.info('Received message from: %s' % message.sender) lines = [prompt] lines.extend(self.COMMAND_HELP_MSG_LIST) message_builder = MessageBuilder() for line in lines: message_builder.add(line) reply(message_builder, message) def track_command(self, message=None): """ Start tracking a phrase against the Buzz API. message must be a valid xmpp.Message or subclass and cannot be null. """ logging.debug('Received message from: %s' % message.sender) subscription = None message_builder = MessageBuilder() if message.arg == '': message_builder.add( XmppHandler.NOTHING_TO_TRACK_MSG ) else: logging.debug( "track_command: calling tracker.track with term '%s'" % message.arg ) subscription = self.tracker.track(message.sender, message.arg) if subscription: message_builder.add( XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (subscription.search_term, subscription.id())) else: message_builder.add('%s <%s>' % (XmppHandler.TRACK_FAILED_MSG, message.body)) reply(message_builder, message) logging.debug( "message.message_to_send = '%s'" % message.message_to_send ) return subscription def untrack_command(self, message=None): logging.info('Received message from: %s' % message.sender) subscription = self.tracker.untrack(message.sender, message.arg) message_builder = MessageBuilder() if subscription: message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id())) else: message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: %s [id]' % XmppHandler.UNTRACK_CMD) reply(message_builder, message) def list_command(self, message=None): logging.info('Received message from: %s' % message.sender) message_builder = MessageBuilder() sender = extract_sender_email_address(message.sender) logging.info('Sender: %s' % sender) subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender) if subscriptions_query.count() > 0: for subscription in subscriptions_query: message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id())) else: message_builder.add(XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG) reply(message_builder, message) def about_command(self, message): logging.info('Received message from: %s' % message.sender) message_builder = MessageBuilder() about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: %s' % (settings.APP_NAME, settings.APP_URL) message_builder.add(about_message) reply(message_builder, message) def post_command(self, message): logging.info('Received message from: %s' % message.sender) message_builder = MessageBuilder() sender = extract_sender_email_address(message.sender) user_token = oauth_handlers.UserToken.find_by_email_address(sender) if not user_token: message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL)) logging.debug('%s has not given access to their Google Buzz account but is attempting to post anyway' % sender) elif not user_token.access_token_string: logging.debug('%s did not complete the process for giving access to their Google Buzz account. Deleting their incomplete token: %s' % (sender, str(user_token))) # User didn't finish the OAuth dance so we make them start again user_token.delete() message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL)) logging.debug('%s did not complete the process for giving access to their Google Buzz account. Deleting their incomplete token.' % sender) else: url = self.buzz_wrapper.post(sender, message.arg) message_builder.add('Posted: %s' % url) reply(message_builder, message) def search_command(self, message): logging.info('Received message from: %s' % message.sender) message_builder = MessageBuilder() sender = extract_sender_email_address(message.sender) logging.info('Sender: %s' % sender) message_builder.add('Search results for %s:' % message.arg) results = self.buzz_wrapper.search(message.arg) for index, result in enumerate(results): title = result['title'] permalink = result['links']['alternate'][0]['href'] line = '%s- %s : %s' % (index+1, title, permalink) message_builder.add(line) reply(message_builder, message) def extract_sender_email_address(message_sender): return message_sender.split('/')[0] def reply(message_builder, message): message_to_send = message_builder.build_message() logging.info('Message that will be sent: %s' % message_to_send) message.reply(message_to_send, raw_xml=False) def send_posts(posts, subscriber, search_term): message_builder = MessageBuilder() for post in posts: xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False) \ No newline at end of file
adewale/Buzz-Chat-Bot
b8fd9fe5e8d657db63be41d15cfdaf71c15f08ea
Use pprint.pformat rather than str to avoid problems with the logging library when it gets an invalid unicode sequence like 'handlers/add.py#L21\xa0is'
diff --git a/xmpp.py b/xmpp.py index 48a8e36..9eb6107 100644 --- a/xmpp.py +++ b/xmpp.py @@ -1,425 +1,431 @@ # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from google.appengine.api import xmpp from google.appengine.ext import db from google.appengine.ext import webapp import logging -import urllib import oauth_handlers +import pprint import pshb +import re import settings import simple_buzz_wrapper -import re +import urllib class Subscription(db.Model): url = db.StringProperty(required=True) search_term = db.StringProperty(required=True) subscriber = db.StringProperty() def id(self): return self.key().id() def __eq__(self, other): if not other: return False return self.id() == other.id() @staticmethod def exists(id): """Return True or False to indicate if a subscription with the given id exists""" if not id: return False return Subscription.get_by_id(int(id)) is not None class Tracker(object): def __init__(self, hub_subscriber=pshb.HubSubscriber()): self.hub_subscriber = hub_subscriber @staticmethod def is_blank(string): """ utility function for determining whether a string is blank (just whitespace) """ return (string is None) or (len(string) == 0) or string.isspace() @staticmethod def extract_number(id): """Convert an id to an integer and return None if the conversion fails.""" if id is None: return None try: id = int(id) except ValueError, e: return None return id def _valid_subscription(self, search_term): return not Tracker.is_blank(search_term) def _subscribe(self, message_sender, search_term): message_sender = extract_sender_email_address(message_sender) url = self._build_subscription_url(search_term) logging.info('Subscribing to: %s for user: %s' % (url, message_sender)) subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender) db.put(subscription) callback_url = self._build_callback_url(subscription) logging.info('Callback URL was: %s' % callback_url) self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url) return subscription def _build_callback_url(self, subscription): return "%s/posts?id=%s" % (settings.APP_URL, subscription.id()) def _build_subscription_url(self, search_term): search_term = urllib.quote(search_term) return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term def track(self, message_sender, search_term): if self._valid_subscription(search_term): return self._subscribe(message_sender, search_term) else: return None def untrack(self, message_sender, id): """ Given an id, untrack takes it and attempts to unsubscribe from the list of tracked items. TODO(julian): you should be able to untrack <term> directly. """ logging.info("Tracker.untrack: id is: '%s'" % id) id_as_int = Tracker.extract_number(id) if id_as_int == None: # TODO(ade) Do a subscription lookup by name here return None subscription = Subscription.get_by_id(id_as_int) if not subscription: return None logging.info('Subscripton: %s' % str(subscription)) if subscription.subscriber != extract_sender_email_address(message_sender): return None subscription.delete() callback_url = self._build_callback_url(subscription) logging.info('Callback URL was: %s' % callback_url) self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url) return subscription class MessageBuilder(object): def __init__(self): self.lines = [] def build_message(self): text = '' for index,line in enumerate(self.lines): text += line if (index+1) < len(self.lines): text += '\n' return text def add(self, line): self.lines.append(line) def build_message_from_post(self, post, search_term): return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url) class SlashlessCommandMessage(xmpp.Message): """ The default message format with GAE xmpp identifies the command as the first non whitespace word. The argument is whatever occurs after that. Design notes: it uses re for tokenization which is a step up from how Message works (that expects a single space character) """ def __init__(self, vars): xmpp.Message.__init__(self, vars) #TODO(julian) make arg and command protected. because __arg and __command are hidden as private #in xmpp.Message, we have to define our own separate instances of these variables #even though all we do is change the property accessors for them. # scm = slashless command message # luckily __arg and __command aren't used elsewhere in Message but # we can't guarantee this so it's a bit of a mess self.__scm_arg = None self.__scm_command = None self.__message_to_send = None # END TODO @staticmethod def extract_command_and_arg_from_string(string): # match any white space and then a word (cmd) # then any white space then everything after that (arg). command = None arg = None results = re.search(r"\s*(\S*)\s*(.*)", string) if results: command = results.group(1) arg = results.group(2) # we didn't find a command and an arg so maybe we'll just find the command # some commands may not have args else: results = re.search(r"\s*(\S*)\s*", string) if results: command = results.group(1) return (command,arg) def __ensure_command_and_args_extracted(self): """ Take the message and identify the command and argument if there is one. In the case of a SlashlessCommandMessage, there is always one -- the first word is the command. """ # cache the values. if not self.__scm_command: self.__scm_command,self.__scm_arg = SlashlessCommandMessage.extract_command_and_arg_from_string(self.body) logging.info("command = '%s', arg = '%s'" %(self.__scm_command,self.__scm_arg)) # These properties are redefined from that defined in xmpp.Message @property def command(self): self.__ensure_command_and_args_extracted() return self.__scm_command @property def arg(self): self.__ensure_command_and_args_extracted() return self.__scm_arg @property def message_to_send(self): """ TODO(julian) rename: this is actually response_message """ return self.__message_to_send def reply(self, message_to_send, raw_xml=False): logging.debug( "SlashlessCommandMessage.reply: message_to_send = %s" % message_to_send) xmpp.Message.reply(self, message_to_send, raw_xml=raw_xml) self.__message_to_send = message_to_send class XmppHandler(webapp.RequestHandler): ABOUT_CMD = 'about' HELP_CMD = 'help' ALTERNATIVE_HELP_CMD = '?' LIST_CMD = 'list' POST_CMD = 'post' TRACK_CMD = 'track' UNTRACK_CMD = 'untrack' SEARCH_CMD = 'search' PERMITTED_COMMANDS = [ABOUT_CMD,HELP_CMD,ALTERNATIVE_HELP_CMD,LIST_CMD,POST_CMD,TRACK_CMD,UNTRACK_CMD, SEARCH_CMD] COMMAND_HELP_MSG_LIST = [ '%s Prints out this message' % HELP_CMD, '%s Prints out this message' % ALTERNATIVE_HELP_CMD, '%s [search term] Starts tracking the given search term and returns the id for your subscription' % TRACK_CMD, '%s [id] Removes your subscription for that id' % UNTRACK_CMD, '%s Lists all search terms and ids currently being tracked by you' % LIST_CMD, '%s Tells you which instance of the Buzz Chat Bot you are using' % ABOUT_CMD, '%s [some message] Posts that message to Buzz' % POST_CMD, '%s [some search term] Searches for that search term on Buzz' ] TRACK_FAILED_MSG = 'Sorry there was a problem with that track command ' NOTHING_TO_TRACK_MSG = "To track a phrase on buzz, you need to enter the phrase :) Please type: track <your phrase to track>" UNKNOWN_COMMAND_MSG = "Sorry, '%s' was not understood. Here are a list of the things you can do:" SUBSCRIPTION_SUCCESS_MSG = 'Tracking: %s with id: %s' LIST_NOT_TRACKING_ANYTHING_MSG = 'You are not tracking anything. To track when a word or phrase appears in Buzz, enter: track <thing of interest>' def __init__(self, hub_subscriber=pshb.HubSubscriber()): self.tracker = Tracker(hub_subscriber=hub_subscriber) def unhandled_command(self, message): """ User entered a command that is not recognised. Tell them this and show help""" self.help_command(message, XmppHandler.UNKNOWN_COMMAND_MSG % message.command ) def _make_wrapper(self, email_address): return oauth_handlers.make_wrapper(email_address) def message_received(self, message): """ Take the message we've received and dispatch it to the appropriate command handler using introspection. E.g. if the command is 'track' it will map to track_command. Args: message: Message: The message that was sent by the user. """ logging.info('Command was: %s' % message.command) command = self._get_canonical_command(message) self.buzz_wrapper = self._make_wrapper(message.sender) if command and command in XmppHandler.PERMITTED_COMMANDS: handler_name = '%s_command' % command handler = getattr(self, handler_name, None) if handler: handler(message) return else: logging.info('No handler available for command: %s' % command) self.unhandled_command(message) def _get_canonical_command(self, message): command = message.command.lower() # The old-style / prefixed commands are honoured as if they were slashless commands. This provides backwards # compatibility for early adopters and people who are used to IRC syntax. if command.startswith('/'): command = command[1:] # Handle aliases for commands if command == XmppHandler.ALTERNATIVE_HELP_CMD: command = XmppHandler.HELP_CMD return command def post(self): """ Redefines post to create a message from our new SlashlessCommandMessage. TODO(julian) xmpp_handlers: redefine the BaseHandler to have a function createMessage which can be overridden this will avoid the code duplicated below """ logging.info("Received chat msg, raw post = '%s'" % self.request.POST) try: # CHANGE this is the only bit that has changed from xmpp_handlers.Message self.xmpp_message = SlashlessCommandMessage(self.request.POST) # END CHANGE except xmpp.InvalidMessageError, e: logging.error("Invalid XMPP request: Missing required field: %s", e[0]) self.error(400) return self.message_received(self.xmpp_message) def handle_exception(self, exception, debug_mode): logging.error('handle_exception: calling webapp.RequestHandler superclass') - webapp.RequestHandler.handle_exception(self, exception, debug_mode) + + # All code that logs the content of the error uses pformat because in situations + # where the message contains non-ASCII characters the use of str() was causing + # an exception in the logging library which would hide the original exception + + logging.error('Exception: %s' % pprint.pformat(exception)) if self.xmpp_message: self.xmpp_message.reply('Oops. Something went wrong. Sorry about that') - logging.error('User visible oops for message: %s' % str(self.xmpp_message.body)) + logging.error('User visible oops for message: %s' % pprint.pformat(self.xmpp_message.body)) def help_command(self, message=None, prompt='We all need a little help sometimes' ): """ Print out the help command. Optionally accepts a message builder so help can be printed out if the user looks like they're having trouble """ logging.info('Received message from: %s' % message.sender) lines = [prompt] lines.extend(self.COMMAND_HELP_MSG_LIST) message_builder = MessageBuilder() for line in lines: message_builder.add(line) reply(message_builder, message) def track_command(self, message=None): """ Start tracking a phrase against the Buzz API. message must be a valid xmpp.Message or subclass and cannot be null. """ logging.debug('Received message from: %s' % message.sender) subscription = None message_builder = MessageBuilder() if message.arg == '': message_builder.add( XmppHandler.NOTHING_TO_TRACK_MSG ) else: logging.debug( "track_command: calling tracker.track with term '%s'" % message.arg ) subscription = self.tracker.track(message.sender, message.arg) if subscription: message_builder.add( XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (subscription.search_term, subscription.id())) else: message_builder.add('%s <%s>' % (XmppHandler.TRACK_FAILED_MSG, message.body)) reply(message_builder, message) logging.debug( "message.message_to_send = '%s'" % message.message_to_send ) return subscription def untrack_command(self, message=None): logging.info('Received message from: %s' % message.sender) subscription = self.tracker.untrack(message.sender, message.arg) message_builder = MessageBuilder() if subscription: message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id())) else: message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: %s [id]' % XmppHandler.UNTRACK_CMD) reply(message_builder, message) def list_command(self, message=None): logging.info('Received message from: %s' % message.sender) message_builder = MessageBuilder() sender = extract_sender_email_address(message.sender) logging.info('Sender: %s' % sender) subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender) if subscriptions_query.count() > 0: for subscription in subscriptions_query: message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id())) else: message_builder.add(XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG) reply(message_builder, message) def about_command(self, message): logging.info('Received message from: %s' % message.sender) message_builder = MessageBuilder() about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: %s' % (settings.APP_NAME, settings.APP_URL) message_builder.add(about_message) reply(message_builder, message) def post_command(self, message): logging.info('Received message from: %s' % message.sender) message_builder = MessageBuilder() sender = extract_sender_email_address(message.sender) user_token = oauth_handlers.UserToken.find_by_email_address(sender) if not user_token: message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL)) logging.debug('%s has not given access to their Google Buzz account but is attempting to post anyway' % sender) elif not user_token.access_token_string: logging.debug('%s did not complete the process for giving access to their Google Buzz account. Deleting their incomplete token: %s' % (sender, str(user_token))) # User didn't finish the OAuth dance so we make them start again user_token.delete() message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL)) logging.debug('%s did not complete the process for giving access to their Google Buzz account. Deleting their incomplete token.' % sender) else: url = self.buzz_wrapper.post(sender, message.arg) message_builder.add('Posted: %s' % url) reply(message_builder, message) def search_command(self, message): logging.info('Received message from: %s' % message.sender) message_builder = MessageBuilder() sender = extract_sender_email_address(message.sender) logging.info('Sender: %s' % sender) message_builder.add('Search results for %s:' % message.arg) results = self.buzz_wrapper.search(message.arg) for index, result in enumerate(results): title = result['title'] permalink = result['links']['alternate'][0]['href'] line = '%s- %s : %s' % (index+1, title, permalink) message_builder.add(line) reply(message_builder, message) def extract_sender_email_address(message_sender): return message_sender.split('/')[0] def reply(message_builder, message): message_to_send = message_builder.build_message() logging.info('Message that will be sent: %s' % message_to_send) message.reply(message_to_send, raw_xml=False) def send_posts(posts, subscriber, search_term): message_builder = MessageBuilder() for post in posts: xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False) \ No newline at end of file