An unfinished system to manage all your paper documentation in an easy way.
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

autodoc.fcgi 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. #!/usr/bin/perl
  2. use strict;
  3. use FCGI;
  4. use JSON;
  5. use DBI;
  6. use GD::Simple;
  7. use Data::Dumper;
  8. use Data::UUID;
  9. use warnings;
  10. $Data::Dumper::Sortkeys = 1;
  11. my $conf = load_conf("../etc/autodoc.json");
  12. my $dbh = sqlconnect($conf->{sql});
  13. my %map = (
  14. api_v1_POST_documents => \&api_v1_POST_documents,
  15. api_v1_POST_documents_id_data => \&api_v1_POST_documents_id_data,
  16. api_v1_GET_documents_id_image => \&api_v1_GET_documents_id_image,
  17. api_v1_GET_pages_image => \&api_v1_GET_pages_image,
  18. api_v1_GET_documents => \&api_v1_GET_documents,
  19. api_v1_GET_documents_id => \&api_v1_GET_documents_id,
  20. api_v1_GET_pages_id => \&api_v1_GET_pages_id,
  21. api_v1_PATCH_documents_id => \&api_v1_PATCH_documents_id,
  22. );
  23. my $request = FCGI::Request();
  24. while($request->Accept() >= 0) {
  25. my $user = $ENV{REMOTE_USER} || 'undefined';
  26. my $qs = parse_querystring($ENV{QUERY_STRING});
  27. my $method = $ENV{REQUEST_METHOD};
  28. # QS sanity check
  29. if ( exists $qs->{id} && $qs->{id} !~ /^\d+$/ ) {
  30. fatal_api_error(400,"invalid id");
  31. }
  32. if ( exists $qs->{maxWidth} && $qs->{maxWidth} !~ /^\d+$/ ) {
  33. fatal_api_error(400,"invalid maxWidth");
  34. }
  35. if ( exists $qs->{maxHeight} && $qs->{maxHeight} !~ /^\d+$/ ) {
  36. fatal_api_error(400,"invalid maxHeight");
  37. }
  38. if ( exists $qs->{pageSize} && $qs->{pageSize} !~ /^\d+$/ ) {
  39. fatal_api_error(400,"invalid pageSize");
  40. }
  41. if ( exists $qs->{pageIndex} && $qs->{pageIndex} !~ /^\d+$/ ) {
  42. fatal_api_error(400,"invalid pageIndex");
  43. }
  44. my $path = [ split(/\//,$ENV{SCRIPT_NAME}) ] if exists $ENV{SCRIPT_NAME};
  45. shift(@{$path});
  46. my $post = parse_post(
  47. \*STDIN,
  48. exists $ENV{CONTENT_LENGTH} ? $ENV{CONTENT_LENGTH} : 0,
  49. exists $ENV{CONTENT_TYPE} ? $ENV{CONTENT_TYPE} : 0
  50. );
  51. my($code, $hdr, $type, $data) = process_query($method, $path, $qs, $post, $user);
  52. #print STDERR Dumper("code",$code,"hdr", $hdr, "type", $type, "data", $data);
  53. $hdr = [ ] if !defined $hdr;
  54. if ( defined $type ) {
  55. if ( $type eq 'application/json' ) {
  56. $data = to_json($data, { utf8 => 1, pretty => 1 });
  57. }
  58. }
  59. send_response($code, $hdr, $type, $data);
  60. }
  61. sub gen_uuid {
  62. my $ug = Data::UUID->new;
  63. return lc($ug->create_str());
  64. }
  65. sub send_response {
  66. my ($code, $hdr, $type, $data) = @_;
  67. printf("Status: %s\r\n", $code);
  68. printf("Content-type: %s\r\n", $type) if defined $type;
  69. printf("Content-length: %i\r\n", length($data)) if defined $data;
  70. foreach ( @{$hdr} ) { printf("%s\r\n",$_); }
  71. printf("\r\n");
  72. print $data if defined $data;
  73. }
  74. sub fatal_api_error {
  75. my($code,$hdr,$type,$body)=api_error(@_);
  76. print STDERR "AUTODOC_FATAL: $body\r\n";
  77. send_response($code, $hdr, $type, $body);
  78. exit;
  79. }
  80. sub load_conf {
  81. my($file) = @_;
  82. my $x='';
  83. open(F,"$file") || fatal_api_error(500,"Failed to load configuration file");
  84. while(<F>) { $x.=$_; }
  85. close(F);
  86. return from_json($x);
  87. }
  88. sub process_query {
  89. my($method, $path, $qs, $post, $user) = @_;
  90. my ($api_version, $path_main, $path_id, $path_sub) = @{$path};
  91. return api_error(404, "Unknown API version") if !defined $api_version;
  92. return api_error(405, "Unknown METHOD") if !defined $method;
  93. return api_error(404, "Unknown API function") if !defined $path_main;
  94. my $func = 'api_' . $api_version . '_' . $method . '_' . $path_main;
  95. $func .= '_id' if defined $path_id;
  96. $func .= '_'.$path_sub if defined $path_sub;
  97. return $map{$func}->($path_id, $qs, $post, $user) if exists $map{$func};
  98. return api_error(404, "Invalid path/method combination");
  99. }
  100. sub db_get_document_object {
  101. my($id) = @_;
  102. my $document;
  103. my @pages;
  104. my @pageids;
  105. my @tags;
  106. my $q = sqlquery($dbh, "SELECT * FROM documents WHERE id = ?", $id);
  107. while(my $hash = $q->fetchrow_hashref()) { $document = $hash; }
  108. $q = sqlquery($dbh, "SELECT * FROM pages WHERE documentId = ?", $id);
  109. while(my $hash = $q->fetchrow_hashref()) { push @pages, $hash; push @pageids, $hash->{id}; }
  110. $q = sqlquery($dbh, "
  111. SELECT tags.tag AS tag
  112. FROM documents_tags LEFT JOIN tags ON documents_tags.tagId = tags.id
  113. WHERE documentId = ? ORDER BY tag", $id);
  114. while(my ($tag) = $q->fetchrow_array()) { push @tags, $tag; }
  115. my %lang;
  116. foreach my $page ( @pages ) {
  117. $q = sqlquery($dbh, "SELECT * FROM pages_lang WHERE pageId = ?", $page->{id});
  118. while(my $hash = $q->fetchrow_hashref()) {
  119. $lang{$hash->{language}}++;
  120. }
  121. }
  122. if ( defined $document ) {
  123. my $out = {
  124. id => $document->{id},
  125. pageId => [ @pageids ],
  126. name => $document->{name},
  127. created => $document->{created},
  128. owner => $document->{owner},
  129. status => $document->{status},
  130. languages => [ keys %lang ],
  131. tags => [ @tags ],
  132. };
  133. return (200, undef, "application/json", $out);
  134. }
  135. return (404, undef, "application/json", "");
  136. }
  137. sub db_get_page_object {
  138. my($id) = @_;
  139. my $out;
  140. my %lang;
  141. my $q = sqlquery($dbh, "SELECT * FROM pages_lang WHERE pageId = ?", $id);
  142. while(my $hash = $q->fetchrow_hashref()) {
  143. $lang{$hash->{language}}++;
  144. }
  145. $q = sqlquery($dbh, "SELECT * FROM pages WHERE documentId = ?", $id);
  146. while(my $hash = $q->fetchrow_hashref()) {
  147. $out = {
  148. id => $id,
  149. documentId => $hash->{documentId},
  150. name => $hash->{name},
  151. created => $hash->{created},
  152. owner => $hash->{owner},
  153. status => $hash->{status},
  154. language => [ keys %lang ],
  155. };
  156. }
  157. if ( exists $out->{id} ) {
  158. return (200, "application/json", $out);
  159. }
  160. return (404, undef, "application/json", "");
  161. }
  162. sub get_page_image {
  163. my($id, $qs) = @_;
  164. my $wh;
  165. my $size;
  166. if ( exists $qs->{maxWidth} ) {
  167. $wh = 'w';
  168. $size = $qs->{maxWidth};
  169. }
  170. elsif ( exists $qs->{maxHeight} ) {
  171. $wh = 'h';
  172. $size = $qs->{maxWidth};
  173. }
  174. my $src;
  175. my $dst;
  176. if ( !defined $id ) {
  177. $src = sprintf("%s/%s",
  178. $conf->{path}{global}, $conf->{path}{error_img});
  179. }
  180. else {
  181. $src = sprintf("%s/%s/%s",
  182. $conf->{path}{global}, $conf->{path}{original}, $id);
  183. }
  184. if ( defined $wh && defined $size ) {
  185. if ( defined $id ) {
  186. $dst = sprintf("%s/%s/%s-%s-%s.jpeg",
  187. $conf->{path}{global}, $conf->{path}{cache}, $id, $wh, $size);
  188. }
  189. else {
  190. $dst = sprintf("%s/%s/error_img-%s-%s.jpeg",
  191. $conf->{path}{global}, $conf->{path}{cache}, $wh, $size);
  192. }
  193. }
  194. my $imgfile;
  195. if ( !defined $dst ) {
  196. $imgfile = $src;
  197. }
  198. else {
  199. if ( ! -r $dst ) {
  200. my $cmd = sprintf("convert %s -resize %s%s %s",
  201. $src,
  202. $wh eq 'h' ? 'x' : '',
  203. $size,
  204. $dst
  205. );
  206. #print STDERR "CMD=$cmd\n";
  207. system($cmd);
  208. }
  209. $imgfile = $dst;
  210. }
  211. my $url = $dst;
  212. $url =~ s/$conf->{path}{global}//;
  213. return $url;
  214. #my $img = '';
  215. #open(IMG, $imgfile) || fatal_api_error(500,"Failed to generate image");
  216. #binmode(IMG);
  217. #while(<IMG>) { $img.=$_; }
  218. #close(IMG);
  219. #return $img;
  220. }
  221. # create an empty document object.
  222. sub api_v1_POST_documents {
  223. my($id, $qs, $post, $user) = @_;
  224. $id = gen_uuid();
  225. my $q = sqlquery($dbh, "
  226. INSERT INTO documents
  227. SET
  228. id = ?,
  229. owner = ?,
  230. status = 'nodata'
  231. ", $id, $user);
  232. return db_get_document_object($id);
  233. }
  234. sub api_v1_POST_documents_id_data {
  235. my($id, $qs, $post, $user) = @_;
  236. my $uuid = gen_uuid();
  237. my $ext = $post->{ctype};
  238. $ext =~ s/.*\///;
  239. my $file = sprintf("%s/%s/%s_%s.%s",
  240. $conf->{path}{global},
  241. $conf->{path}{queue},
  242. $id, $uuid, $ext);
  243. open(F,'>'.$file);
  244. print F $post->{data};
  245. close(F);
  246. return (200, undef, "application/json", { })
  247. }
  248. # get document image/thumbnail
  249. sub api_v1_GET_documents_id_image {
  250. my($id, $qs, $post, $user) = @_;
  251. my $pageid;
  252. my $q = sqlquery($dbh, "SELECT id FROM pages WHERE documentId = ? ORDER BY id DESC LIMIT 1", $id);
  253. while(my($myid)=$q->fetchrow_array()) {
  254. $pageid = $myid;
  255. }
  256. return api_v1_GET_pages_id_image($pageid, $qs, $post, $user);
  257. }
  258. # get page image/thumbnail
  259. sub api_v1_GET_pages_id_image {
  260. my($id, $qs, $post, $user) = @_;
  261. #return (200, "image/jpeg", get_page_image($id, $qs));
  262. my $url = get_page_image($id, $qs);
  263. return (302, [ "Location: $url" ]);
  264. }
  265. # get a list of document objects
  266. sub api_v1_GET_documents {
  267. my($id, $qs, $post, $user) = @_;
  268. $qs->{pageSize} = $conf->{query}{pageSize} if !exists $qs->{pageSize};
  269. $qs->{pageIndex} = $conf->{query}{pageIndex} if !exists $qs->{pageIndex};
  270. my @out;
  271. my $q = sqlquery($dbh, "SELECT id FROM documents LIMIT ?,?",
  272. $qs->{pageSize} * $qs->{pageIndex},
  273. $qs->{pageSize});
  274. while(my ($id) = $q->fetchrow_array()) {
  275. my ($code, $ct, $body) = db_get_document_object($id);
  276. push @out, $body;
  277. }
  278. return (
  279. 200,
  280. undef,
  281. "application/json",
  282. \@out
  283. );
  284. }
  285. # get a single document object
  286. sub api_v1_GET_documents_id {
  287. my($id, $qs, $post, $user) = @_;
  288. return db_get_document_object($id);
  289. }
  290. # get a specific page
  291. sub api_v1_GET_pages_id {
  292. my($id, $qs, $post, $user) = @_;
  293. return db_get_page_object($id);
  294. }
  295. # change document properties
  296. sub api_v1_PATCH_documents_id {
  297. my($id, $qs, $post, $user) = @_;
  298. if ( exists $qs->{addTags} ) {
  299. my $tags = get_array($qs->{addTags});
  300. foreach my $tag ( @{$tags} ) {
  301. sqlquery($dbh, "CALL tag_add(?,?)", $id, $tag);
  302. }
  303. }
  304. if ( exists $qs->{deleteTags} ) {
  305. my $tags = get_array($qs->{deleteTags});
  306. foreach my $tag ( @{$tags} ) {
  307. sqlquery($dbh, "CALL tag_del(?,?)", $id, $tag);
  308. }
  309. }
  310. if ( exists $qs->{name} ) {
  311. sqlquery($dbh, "UPDATE documents SET name = ? WHERE id = ?",
  312. $qs->{name}, $id);
  313. }
  314. return (200);
  315. }
  316. sub get_array {
  317. my($x) = @_;
  318. my @arr;
  319. if ( ref $x eq 'ARRAY' ) {
  320. @arr = @{$x};
  321. }
  322. else {
  323. @arr = [ $x ];
  324. }
  325. return \@arr;
  326. }
  327. sub api_error {
  328. my($code, $text)=@_;
  329. my %deftext = (
  330. "000" => "An error produced an internal error, cascading errors over errors",
  331. "404" => "No such API path"
  332. );
  333. $code = "000" if !defined $code;
  334. $text = $deftext{$code} if ( !defined $text || $code eq "000" );
  335. return ( $code, undef, "text/plain", $text . "\r\n" );
  336. }
  337. sub parse_querystring {
  338. my($in) = @_;
  339. my %out;
  340. if ( defined $in && length $in ) {
  341. foreach(split(/&/,$in)) {
  342. my($name,$value) = split(/=/);
  343. $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
  344. # handle arrays
  345. if ( exists $out{$name} ) {
  346. if ( ! ref $out{$name} ) {
  347. my $old = $out{$name};
  348. $out{$name} = [ $old ];
  349. }
  350. push @{$out{$name}}, $value;
  351. }
  352. else {
  353. $out{$name}=$value;
  354. }
  355. }
  356. }
  357. return \%out;
  358. }
  359. sub parse_post {
  360. my($fd, $len, $ct) = @_;
  361. my $data = '';
  362. while ( $len > 0 ) {
  363. my $buf;
  364. my $read = read($fd, $buf, $len);
  365. $len -= $read;
  366. $data .= $buf;
  367. }
  368. if ( $ct eq 'application/json' ) {
  369. my $tmp = from_json($data);
  370. $data = $tmp;
  371. }
  372. return { ctype => $ct, len => $len, data => $data};
  373. }
  374. sub sqlconnect {
  375. my($sql) = @_;
  376. my $dsn = "DBI:mysql:database=$sql->{base};host=$sql->{host}";
  377. my $dbh = DBI->connect($dsn, $sql->{user}, $sql->{pass}) || \\
  378. fatal_api_error(500,"Failed to connect to database");
  379. return $dbh;
  380. }
  381. sub sqlquery {
  382. my $dbh = shift;
  383. my $query = shift;
  384. my @args = @_;
  385. #print STDERR "$query\n";
  386. my $sth = $dbh->prepare($query) || fatal_api_error(500,"Failed to execute SQL query");
  387. $sth->execute(@args) || fatal_api_error(500,"Failed to execute SQL query");
  388. return $sth;
  389. }