An unfinished system to manage all your paper documentation in an easy way.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

autodoc.fcgi 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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, "
  109. SELECT p.*
  110. FROM pages p
  111. JOIN documents_pages dp
  112. ON p.id = dp.pageId
  113. WHERE dp.documentId = ?", $id);
  114. while(my $hash = $q->fetchrow_hashref()) {
  115. my $clean = { };
  116. foreach my $name ( keys %{$hash} ) {
  117. if ( $name =~ /^pages\.(.*)/ ) {
  118. my $newname = $1;
  119. $clean->{$newname} = $hash->{$name};
  120. }
  121. }
  122. push @pages, $clean; push @pageids, $clean->{id};
  123. }
  124. $q = sqlquery($dbh, "
  125. SELECT tags.tag AS tag
  126. FROM documents_tags JOIN tags ON documents_tags.tagId = tags.id
  127. WHERE documentId = ? ORDER BY tag", $id);
  128. while(my ($tag) = $q->fetchrow_array()) { push @tags, $tag; }
  129. my %lang;
  130. foreach my $page ( @pages ) {
  131. $q = sqlquery($dbh, "
  132. SELECT
  133. SUM(pw.count) AS count
  134. l.short AS lang
  135. FROM pages_words pw
  136. JOIN words w ON pw.wordID = w.id
  137. JOIN lang l ON w.langId = l.id
  138. WHERE pw.pageId = ?", $page->{id});
  139. while(my $h = $q->fetchrow_hashref()) {
  140. $lang{$h->{lang}}=$h->{count};
  141. }
  142. }
  143. if ( defined $document ) {
  144. my $out = {
  145. id => $document->{id},
  146. pageId => [ @pageids ],
  147. name => $document->{name},
  148. created => $document->{created},
  149. owner => $document->{owner},
  150. status => $document->{status},
  151. languages => [ keys %lang ],
  152. tags => [ @tags ],
  153. };
  154. return (200, undef, "application/json", $out);
  155. }
  156. return (404, undef, "application/json", "");
  157. }
  158. sub db_get_page_object {
  159. my($id) = @_;
  160. my $out;
  161. my %lang;
  162. my $q = sqlquery($dbh, "SELECT * FROM pages_lang WHERE pageId = ?", $id);
  163. while(my $hash = $q->fetchrow_hashref()) {
  164. $lang{$hash->{language}}++;
  165. }
  166. $q = sqlquery($dbh, "SELECT * FROM pages WHERE documentId = ?", $id);
  167. while(my $hash = $q->fetchrow_hashref()) {
  168. $out = {
  169. id => $id,
  170. documentId => $hash->{documentId},
  171. name => $hash->{name},
  172. created => $hash->{created},
  173. owner => $hash->{owner},
  174. status => $hash->{status},
  175. language => [ keys %lang ],
  176. };
  177. }
  178. if ( exists $out->{id} ) {
  179. return (200, "application/json", $out);
  180. }
  181. return (404, undef, "application/json", "");
  182. }
  183. sub get_page_image {
  184. my($id, $qs) = @_;
  185. my $wh;
  186. my $size;
  187. if ( exists $qs->{maxWidth} ) {
  188. $wh = 'w';
  189. $size = $qs->{maxWidth};
  190. }
  191. elsif ( exists $qs->{maxHeight} ) {
  192. $wh = 'h';
  193. $size = $qs->{maxWidth};
  194. }
  195. my $src;
  196. my $dst;
  197. if ( !defined $id ) {
  198. $src = sprintf("%s/%s",
  199. $conf->{path}{global}, $conf->{path}{error_img});
  200. }
  201. else {
  202. $src = sprintf("%s/%s/%s",
  203. $conf->{path}{global}, $conf->{path}{original}, $id);
  204. }
  205. if ( defined $wh && defined $size ) {
  206. if ( defined $id ) {
  207. $dst = sprintf("%s/%s/%s-%s-%s.jpeg",
  208. $conf->{path}{global}, $conf->{path}{cache}, $id, $wh, $size);
  209. }
  210. else {
  211. $dst = sprintf("%s/%s/error_img-%s-%s.jpeg",
  212. $conf->{path}{global}, $conf->{path}{cache}, $wh, $size);
  213. }
  214. }
  215. my $imgfile;
  216. if ( !defined $dst ) {
  217. $imgfile = $src;
  218. }
  219. else {
  220. if ( ! -r $dst ) {
  221. my $cmd = sprintf("convert %s -resize %s%s %s",
  222. $src,
  223. $wh eq 'h' ? 'x' : '',
  224. $size,
  225. $dst
  226. );
  227. #print STDERR "CMD=$cmd\n";
  228. system($cmd);
  229. }
  230. $imgfile = $dst;
  231. }
  232. my $url = $dst;
  233. $url =~ s/$conf->{path}{global}//;
  234. return $url;
  235. #my $img = '';
  236. #open(IMG, $imgfile) || fatal_api_error(500,"Failed to generate image");
  237. #binmode(IMG);
  238. #while(<IMG>) { $img.=$_; }
  239. #close(IMG);
  240. #return $img;
  241. }
  242. # create an empty document object.
  243. sub api_v1_POST_documents {
  244. my($id, $qs, $post, $user) = @_;
  245. my $docid;
  246. my $q = sqlquery($dbh, "CALL create_document(?)", $user);
  247. while(my($id) = $q->fetchrow_array()) {
  248. $docid = $id;
  249. }
  250. return db_get_document_object($docid);
  251. }
  252. sub api_v1_POST_documents_id_data {
  253. my($id, $qs, $post, $user) = @_;
  254. my $uuid = gen_uuid();
  255. my $ext = $post->{ctype};
  256. $ext =~ s/.*\///;
  257. my $file = sprintf("%s/%s/%s_%s.%s",
  258. $conf->{path}{global},
  259. $conf->{path}{queue},
  260. $id, $uuid, $ext);
  261. open(F,'>'.$file);
  262. print F $post->{data};
  263. close(F);
  264. return (200, undef, "application/json", { })
  265. }
  266. # get document image/thumbnail
  267. sub api_v1_GET_documents_id_image {
  268. my($id, $qs, $post, $user) = @_;
  269. my $pageid;
  270. my $q = sqlquery($dbh, "CALL get_primary_page(?)", $id);
  271. while(my($myid)=$q->fetchrow_array()) {
  272. $pageid = $myid;
  273. }
  274. return api_v1_GET_pages_id_image($pageid, $qs, $post, $user);
  275. }
  276. # get page image/thumbnail
  277. sub api_v1_GET_pages_id_image {
  278. my($id, $qs, $post, $user) = @_;
  279. #return (200, "image/jpeg", get_page_image($id, $qs));
  280. my $url = get_page_image($id, $qs);
  281. return (302, [ "Location: $url" ]);
  282. }
  283. # get a list of document objects
  284. sub api_v1_GET_documents {
  285. my($id, $qs, $post, $user) = @_;
  286. $qs->{pageSize} = $conf->{query}{pageSize} if !exists $qs->{pageSize};
  287. $qs->{pageIndex} = $conf->{query}{pageIndex} if !exists $qs->{pageIndex};
  288. my @out;
  289. my $q = sqlquery($dbh, "SELECT id FROM documents LIMIT ?,?",
  290. $qs->{pageSize} * $qs->{pageIndex},
  291. $qs->{pageSize});
  292. while(my ($id) = $q->fetchrow_array()) {
  293. my ($code, $ct, $body) = db_get_document_object($id);
  294. push @out, $body;
  295. }
  296. return (
  297. 200,
  298. undef,
  299. "application/json",
  300. \@out
  301. );
  302. }
  303. # get a single document object
  304. sub api_v1_GET_documents_id {
  305. my($id, $qs, $post, $user) = @_;
  306. return db_get_document_object($id);
  307. }
  308. # get a specific page
  309. sub api_v1_GET_pages_id {
  310. my($id, $qs, $post, $user) = @_;
  311. return db_get_page_object($id);
  312. }
  313. # change document properties
  314. sub api_v1_PATCH_documents_id {
  315. my($id, $qs, $post, $user) = @_;
  316. if ( exists $qs->{addTags} ) {
  317. my $tags = get_array($qs->{addTags});
  318. foreach my $tag ( @{$tags} ) {
  319. sqlquery($dbh, "CALL add_tag(?,?)", $id, $tag);
  320. }
  321. }
  322. if ( exists $qs->{deleteTags} ) {
  323. my $tags = get_array($qs->{deleteTags});
  324. foreach my $tag ( @{$tags} ) {
  325. sqlquery($dbh, "CALL delete_tag(?,?)", $id, $tag);
  326. }
  327. }
  328. if ( exists $qs->{name} ) {
  329. sqlquery($dbh, "UPDATE documents SET name = ? WHERE id = ?",
  330. $qs->{name}, $id);
  331. }
  332. return (200);
  333. }
  334. sub get_array {
  335. my($x) = @_;
  336. my @arr;
  337. if ( ref $x eq 'ARRAY' ) {
  338. @arr = @{$x};
  339. }
  340. else {
  341. @arr = [ $x ];
  342. }
  343. return \@arr;
  344. }
  345. sub api_error {
  346. my($code, $text)=@_;
  347. my %deftext = (
  348. "000" => "An error produced an internal error, cascading errors over errors",
  349. "404" => "No such API path"
  350. );
  351. $code = "000" if !defined $code;
  352. $text = $deftext{$code} if ( !defined $text || $code eq "000" );
  353. return ( $code, undef, "text/plain", $text . "\r\n" );
  354. }
  355. sub parse_querystring {
  356. my($in) = @_;
  357. my %out;
  358. if ( defined $in && length $in ) {
  359. foreach(split(/&/,$in)) {
  360. my($name,$value) = split(/=/);
  361. $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
  362. # handle arrays
  363. if ( exists $out{$name} ) {
  364. if ( ! ref $out{$name} ) {
  365. my $old = $out{$name};
  366. $out{$name} = [ $old ];
  367. }
  368. push @{$out{$name}}, $value;
  369. }
  370. else {
  371. $out{$name}=$value;
  372. }
  373. }
  374. }
  375. return \%out;
  376. }
  377. sub parse_post {
  378. my($fd, $len, $ct) = @_;
  379. my $data = '';
  380. while ( $len > 0 ) {
  381. my $buf;
  382. my $read = read($fd, $buf, $len);
  383. $len -= $read;
  384. $data .= $buf;
  385. }
  386. if ( $ct eq 'application/json' ) {
  387. my $tmp = from_json($data);
  388. $data = $tmp;
  389. }
  390. return { ctype => $ct, len => $len, data => $data};
  391. }
  392. sub sqlconnect {
  393. my($sql) = @_;
  394. my $dsn = "DBI:mysql:database=$sql->{base};host=$sql->{host}";
  395. my $dbh = DBI->connect($dsn, $sql->{user}, $sql->{pass}) || \\
  396. fatal_api_error(500,"Failed to connect to database");
  397. return $dbh;
  398. }
  399. sub sqlquery {
  400. my $dbh = shift;
  401. my $query = shift;
  402. my @args = @_;
  403. #print STDERR "$query\n";
  404. my $sth = $dbh->prepare($query) || fatal_api_error(500,"Failed to execute SQL query");
  405. $sth->execute(@args) || fatal_api_error(500,"Failed to execute SQL query");
  406. return $sth;
  407. }