]> git.tuebingen.mpg.de Git - paraslash.git/blob - aft.c
ce84ef0a47c822256ab52283c6259e0e787c9e37
[paraslash.git] / aft.c
1 /*
2  * Copyright (C) 2007 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file aft.c Audio file table functions. */
8
9 #include "para.h"
10 #include "error.h"
11 #include <sys/mman.h>
12 #include <fnmatch.h>
13 #include "afh.h"
14 #include "afs.h"
15 #include "net.h"
16 #include "string.h"
17 #include "vss.h"
18
19 static struct osl_table *audio_file_table;
20
21 /** The different sorting methods of the ls command. */
22 enum ls_sorting_method {
23         /** -sp (default) */
24         LS_SORT_BY_PATH,
25         /** -ss */
26         LS_SORT_BY_SCORE,
27         /** -sl */
28         LS_SORT_BY_LAST_PLAYED,
29         /** -sn */
30         LS_SORT_BY_NUM_PLAYED,
31         /** -sf */
32         LS_SORT_BY_FREQUENCY,
33         /** -sc */
34         LS_SORT_BY_CHANNELS,
35         /** -si */
36         LS_SORT_BY_IMAGE_ID,
37         /** -sy */
38         LS_SORT_BY_LYRICS_ID,
39         /** -sb */
40         LS_SORT_BY_BITRATE,
41         /** -sd */
42         LS_SORT_BY_DURATION,
43         /** -sa */
44         LS_SORT_BY_AUDIO_FORMAT,
45         /** -sh */
46         LS_SORT_BY_HASH,
47 };
48
49 /** The different listing modes of the ls command. */
50 enum ls_listing_mode {
51         /** Default listing mode. */
52         LS_MODE_SHORT,
53         /** -l or -ll */
54         LS_MODE_LONG,
55         /** -lv */
56         LS_MODE_VERBOSE,
57         /** -lm */
58         LS_MODE_MBOX
59 };
60
61 /** The flags accepted by the ls command. */
62 enum ls_flags {
63         /** -p */
64         LS_FLAG_FULL_PATH = 1,
65         /** -a */
66         LS_FLAG_ADMISSIBLE_ONLY = 2,
67         /** -r */
68         LS_FLAG_REVERSE = 4,
69 };
70
71 /**
72  * The size of the individual output fields of the ls command.
73  *
74  * These depend on the actual content being listed. If, for instance only files
75  * with duration less than an hour are being listed, then the duration with is
76  * made smaller because then the duration is listed as mm:ss rather than
77  * hh:mm:ss.
78  */
79 struct ls_widths {
80         /** size of the score field. */
81         unsigned short score_width;
82         /** size of the image id field. */
83         unsigned short image_id_width;
84         /** size of the lyrics id field. */
85         unsigned short lyrics_id_width;
86         /** size of the bitrate field. */
87         unsigned short bitrate_width;
88         /** size of the frequency field. */
89         unsigned short frequency_width;
90         /** size of the duration field. */
91         unsigned short duration_width;
92         /** size of the num played field. */
93         unsigned short num_played_width;
94 };
95
96 /** Data passed to the different compare functions (called by qsort()). */
97 struct ls_data {
98         /** Usual audio format handler information. */
99         struct audio_format_info afhi;
100         /** Audio file selector information. */
101         struct afs_info afsi;
102         /** The full path of the audio file. */
103         char *path;
104         /** The score value (if -a was given). */
105         long score;
106         /** The sha1 hash of audio file. */
107         HASH_TYPE *hash;
108 };
109
110 struct ls_options {
111         unsigned flags;
112         enum ls_sorting_method sorting;
113         enum ls_listing_mode mode;
114         char **patterns;
115         int num_patterns;
116         struct ls_widths widths;
117         uint32_t array_size;
118         uint32_t num_matching_paths;
119         struct ls_data *data;
120         struct ls_data **data_ptr;
121 };
122
123 /**
124  * Describes the layout of the mmapped-afs info struct.
125  *
126  * \sa struct afs_info.
127  */
128 enum afsi_offsets {
129         /** Where .last_played is stored. */
130         AFSI_LAST_PLAYED_OFFSET = 0,
131         /** Storage position of the attributes bitmap. */
132         AFSI_ATTRIBUTES_OFFSET = 8,
133         /** Storage position of the .num_played field. */
134         AFSI_NUM_PLAYED_OFFSET = 16,
135         /** Storage position of the .image_id field. */
136         AFSI_IMAGE_ID_OFFSET = 20,
137         /** Storage position of the .lyrics_id field. */
138         AFSI_LYRICS_ID_OFFSET = 24,
139         /** Storage position of the .audio_format_id field. */
140         AFSI_AUDIO_FORMAT_ID_OFFSET = 28,
141         /** On-disk storage space needed. */
142         AFSI_SIZE = 29
143 };
144
145 /**
146  * Convert a struct afs_info to an osl object.
147  *
148  * \param afsi Pointer to the audio file info to be converted.
149  * \param obj Result pointer.
150  *
151  * \sa load_afsi().
152  */
153 void save_afsi(struct afs_info *afsi, struct osl_object *obj)
154 {
155         char *buf = obj->data;
156
157         write_u64(buf + AFSI_LAST_PLAYED_OFFSET, afsi->last_played);
158         write_u64(buf + AFSI_ATTRIBUTES_OFFSET, afsi->attributes);
159         write_u32(buf + AFSI_NUM_PLAYED_OFFSET, afsi->num_played);
160         write_u32(buf + AFSI_IMAGE_ID_OFFSET, afsi->image_id);
161         write_u32(buf + AFSI_LYRICS_ID_OFFSET, afsi->lyrics_id);
162         write_u8(buf + AFSI_AUDIO_FORMAT_ID_OFFSET,
163                 afsi->audio_format_id);
164 }
165
166 /**
167  *  Get the audio file selector info struct stored in an osl object.
168  *
169  * \param afsi Points to the audio_file info structure to be filled in.
170  * \param obj The osl object holding the data.
171  *
172  * \return Positive on success, negative on errors. Possible errors: \p E_BAD_AFS.
173  *
174  * \sa save_afsi().
175  */
176 int load_afsi(struct afs_info *afsi, struct osl_object *obj)
177 {
178         char *buf = obj->data;
179         if (obj->size < AFSI_SIZE)
180                 return -E_BAD_AFSI;
181         afsi->last_played = read_u64(buf + AFSI_LAST_PLAYED_OFFSET);
182         afsi->attributes = read_u64(buf + AFSI_ATTRIBUTES_OFFSET);
183         afsi->num_played = read_u32(buf + AFSI_NUM_PLAYED_OFFSET);
184         afsi->image_id = read_u32(buf + AFSI_IMAGE_ID_OFFSET);
185         afsi->lyrics_id = read_u32(buf + AFSI_LYRICS_ID_OFFSET);
186         afsi->audio_format_id = read_u8(buf +
187                 AFSI_AUDIO_FORMAT_ID_OFFSET);
188         return 1;
189 }
190
191 /** The columns of the audio file table. */
192 enum audio_file_table_columns {
193         /** The hash on the content of the audio file. */
194         AFTCOL_HASH,
195         /** The full path in the filesystem. */
196         AFTCOL_PATH,
197         /** The audio file selector info. */
198         AFTCOL_AFSI,
199         /** The audio format handler info. */
200         AFTCOL_AFHI,
201         /** The chunk table info and the chunk table of the audio file. */
202         AFTCOL_CHUNKS,
203         /** The number of columns of this table. */
204         NUM_AFT_COLUMNS
205 };
206
207 static struct osl_column_description aft_cols[] = {
208         [AFTCOL_HASH] = {
209                 .storage_type = OSL_MAPPED_STORAGE,
210                 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE | OSL_UNIQUE,
211                 .name = "hash",
212                 .compare_function = osl_hash_compare,
213                 .data_size = HASH_SIZE
214         },
215         [AFTCOL_PATH] = {
216                 .storage_type = OSL_MAPPED_STORAGE,
217                 .storage_flags = OSL_RBTREE | OSL_UNIQUE,
218                 .name = "path",
219                 .compare_function = string_compare,
220         },
221         [AFTCOL_AFSI] = {
222                 .storage_type = OSL_MAPPED_STORAGE,
223                 .storage_flags = OSL_FIXED_SIZE,
224                 .name = "afs_info",
225                 .data_size = AFSI_SIZE
226         },
227         [AFTCOL_AFHI] = {
228                 .storage_type = OSL_MAPPED_STORAGE,
229                 .name = "afh_info",
230         },
231         [AFTCOL_CHUNKS] = {
232                 .storage_type = OSL_DISK_STORAGE,
233                 .name = "chunks",
234         }
235 };
236
237 static struct osl_table_description audio_file_table_desc = {
238         .name = "audio_files",
239         .num_columns = NUM_AFT_COLUMNS,
240         .flags = OSL_LARGE_TABLE,
241         .column_descriptions = aft_cols
242 };
243
244 /* We don't want * dot or dot-dot anywhere. */
245 static int verify_dotfile(const char *rest)
246 {
247         /*
248          * The first character was '.', but that has already been discarded, we
249          * now test the rest.
250          */
251         switch (*rest) {
252         case '\0': case '/': /* /foo/. and /foo/./bar are not ok */
253                 return -1;
254         case '.': /* path start with /foo/.. */
255                 if (rest[1] == '\0' || rest[1] == '/')
256                         return -1; /* /foo/.. or /foo/../bar are not ok */
257                 /* /foo/..bar is ok */
258         }
259         return 1;
260 }
261
262 /*
263  * We fundamentally don't like some paths: We don't want double slashes or
264  * slashes at the end that can make pathnames ambiguous.
265  */
266 static int verify_path(const char *orig_path, char **resolved_path)
267 {
268         char c;
269         size_t len;
270         char *path;
271
272         if (*orig_path != '/') /* we only accept absolute paths */
273                 return -E_BAD_PATH;
274         len = strlen(orig_path);
275         *resolved_path = para_strdup(orig_path);
276         path = *resolved_path;
277         while (len > 1 && path[--len] == '/')
278                 path[len] = '\0'; /* remove slash at the end */
279         c = *path++;
280         while (c) {
281                 if (c == '/') {
282                         c = *path++;
283                         switch (c) {
284                         case '/': /* double slash */
285                                 goto bad_path;
286                         case '.':
287                                 if (verify_dotfile(path) < 0)
288                                         goto bad_path;
289                         default:
290                                 continue;
291                         }
292                 }
293                 c = *path++;
294         }
295         return 1;
296 bad_path:
297         free(*resolved_path);
298         return -E_BAD_PATH;
299 }
300
301 enum afhi_offsets {
302         AFHI_SECONDS_TOTAL_OFFSET = 0,
303         AFHI_BITRATE_OFFSET = 4,
304         AFHI_FREQUENCY_OFFSET = 8,
305         AFHI_CHANNELS_OFFSET = 12,
306         AFHI_INFO_STRING_OFFSET = 13,
307         MIN_AFHI_SIZE = 14
308 };
309
310 static unsigned sizeof_afhi_buf(const struct audio_format_info *afhi)
311 {
312         if (!afhi)
313                 return 0;
314         return strlen(afhi->info_string) + MIN_AFHI_SIZE;
315 }
316
317 static void save_afhi(struct audio_format_info *afhi, char *buf)
318 {
319         if (!afhi)
320                 return;
321         write_u32(buf + AFHI_SECONDS_TOTAL_OFFSET,
322                 afhi->seconds_total);
323         write_u32(buf + AFHI_BITRATE_OFFSET, afhi->bitrate);
324         write_u32(buf + AFHI_FREQUENCY_OFFSET, afhi->frequency);
325         write_u8(buf + AFHI_CHANNELS_OFFSET, afhi->channels);
326         strcpy(buf + AFHI_INFO_STRING_OFFSET, afhi->info_string); /* OK */
327         PARA_DEBUG_LOG("last byte written: %p\n", buf + AFHI_INFO_STRING_OFFSET + strlen(afhi->info_string));
328 }
329
330 static void load_afhi(const char *buf, struct audio_format_info *afhi)
331 {
332         afhi->seconds_total = read_u32(buf + AFHI_SECONDS_TOTAL_OFFSET);
333         afhi->bitrate = read_u32(buf + AFHI_BITRATE_OFFSET);
334         afhi->frequency = read_u32(buf + AFHI_FREQUENCY_OFFSET);
335         afhi->channels = read_u8(buf + AFHI_CHANNELS_OFFSET);
336         strcpy(afhi->info_string, buf + AFHI_INFO_STRING_OFFSET);
337 }
338
339 static unsigned sizeof_chunk_info_buf(struct audio_format_info *afhi)
340 {
341         if (!afhi)
342                 return 0;
343         return 4 * afhi->chunks_total + 20;
344
345 }
346
347 /** The offsets of the data contained in the AFTCOL_CHUNKS column. */
348 enum chunk_info_offsets{
349         /** The total number of chunks (4 bytes). */
350         CHUNKS_TOTAL_OFFSET = 0,
351         /** The length of the audio file header (4 bytes). */
352         HEADER_LEN_OFFSET = 4,
353         /** The start of the audio file header (4 bytes). */
354         HEADER_OFFSET_OFFSET = 8,
355         /** The seconds part of the chunk time (4 bytes). */
356         CHUNK_TV_TV_SEC_OFFSET = 12,
357         /** The microseconds part of the chunk time (4 bytes). */
358         CHUNK_TV_TV_USEC = 16,
359         /** Chunk table entries start here. */
360         CHUNK_TABLE_OFFSET = 20,
361 };
362
363 /* TODO: audio format handlers could just produce this */
364 static void save_chunk_info(struct audio_format_info *afhi, char *buf)
365 {
366         int i;
367
368         if (!afhi)
369                 return;
370         write_u32(buf + CHUNKS_TOTAL_OFFSET, afhi->chunks_total);
371         write_u32(buf + HEADER_LEN_OFFSET, afhi->header_len);
372         write_u32(buf + HEADER_OFFSET_OFFSET, afhi->header_offset);
373         write_u32(buf + CHUNK_TV_TV_SEC_OFFSET, afhi->chunk_tv.tv_sec);
374         write_u32(buf + CHUNK_TV_TV_USEC, afhi->chunk_tv.tv_usec);
375         for (i = 0; i < afhi->chunks_total; i++)
376                 write_u32(buf + CHUNK_TABLE_OFFSET + 4 * i, afhi->chunk_table[i]);
377 }
378
379 static int load_chunk_info(struct osl_object *obj, struct audio_format_info *afhi)
380 {
381         char *buf = obj->data;
382         int i;
383
384         if (obj->size < CHUNK_TABLE_OFFSET)
385                 return -E_BAD_DATA_SIZE;
386
387         afhi->chunks_total = read_u32(buf + CHUNKS_TOTAL_OFFSET);
388         afhi->header_len = read_u32(buf + HEADER_LEN_OFFSET);
389         afhi->header_offset = read_u32(buf + HEADER_OFFSET_OFFSET);
390         afhi->chunk_tv.tv_sec = read_u32(buf + CHUNK_TV_TV_SEC_OFFSET);
391         afhi->chunk_tv.tv_usec = read_u32(buf + CHUNK_TV_TV_USEC);
392
393         if (afhi->chunks_total * 4 + CHUNK_TABLE_OFFSET > obj->size)
394                 return -E_BAD_DATA_SIZE;
395         afhi->chunk_table = para_malloc(afhi->chunks_total * sizeof(size_t));
396         for (i = 0; i < afhi->chunks_total; i++)
397                 afhi->chunk_table[i] = read_u32(buf + CHUNK_TABLE_OFFSET + 4 * i);
398         return 1;
399 }
400
401 /**
402  * Get the row of the audio file table corresponding to the given path.
403  *
404  * \param path The full path of the audio file.
405  * \param row Result pointer.
406  *
407  * \return The return value of the underlying call to osl_get_row().
408  */
409 int aft_get_row_of_path(const char *path, struct osl_row **row)
410 {
411         struct osl_object obj = {.data = (char *)path, .size = strlen(path) + 1};
412
413         return osl_get_row(audio_file_table, AFTCOL_PATH, &obj, row);
414 }
415
416 /**
417  * Get the row of the audio file table corresponding to the given hash value.
418  *
419  * \param hash The hash value of the desired audio file.
420  * \param row resul pointer.
421  *
422  * \return The return value of the underlying call to osl_get_row().
423  */
424 int aft_get_row_of_hash(HASH_TYPE *hash, struct osl_row **row)
425 {
426         const struct osl_object obj = {.data = hash, .size = HASH_SIZE};
427         return osl_get_row(audio_file_table, AFTCOL_HASH, &obj, row);
428 }
429
430 /**
431  * Get the osl object holding the audio file selector info of a row.
432  *
433  * \param row Pointer to a row in the audio file table.
434  * \param obj Result pointer.
435  *
436  * \return The return value of the underlying call to osl_get_object().
437  */
438 int get_afsi_object_of_row(const struct osl_row *row, struct osl_object *obj)
439 {
440         return osl_get_object(audio_file_table, row, AFTCOL_AFSI, obj);
441 }
442
443 /**
444  * Get the osl object holding the audio file selector info, given a path.
445  *
446  *
447  * \param path The full path of the audio file.
448  * \param obj Result pointer.
449  *
450  * \return Positive on success, negative on errors.
451  */
452 int get_afsi_object_of_path(const char *path, struct osl_object *obj)
453 {
454         struct osl_row *row;
455         int ret = aft_get_row_of_path(path, &row);
456         if (ret < 0)
457                 return ret;
458         return get_afsi_object_of_row(row, obj);
459 }
460
461 /**
462  * Get the audio file selector info, given a row of the audio file table.
463  *
464  * \param row Pointer to a row in the audio file table.
465  * \param afsi Result pointer.
466  *
467  * \return Positive on success, negative on errors.
468  */
469 int get_afsi_of_row(const struct osl_row *row, struct afs_info *afsi)
470 {
471         struct osl_object obj;
472         int ret = get_afsi_object_of_row(row, &obj);
473         if (ret < 0)
474                 return ret;
475         return load_afsi(afsi, &obj);
476 }
477
478 /**
479  * Get the audio file selector info, given the path of an audio table.
480  *
481  * \param path The full path of the audio file.
482  * \param afsi Result pointer.
483  *
484  * \return Positive on success, negative on errors.
485  */
486 int get_afsi_of_path(const char *path, struct afs_info *afsi)
487 {
488         struct osl_object obj;
489         int ret = get_afsi_object_of_path(path, &obj);
490         if (ret < 0)
491                 return ret;
492         return load_afsi(afsi, &obj);
493 }
494
495 /**
496  * Get the path of an audio file, given a row of the audio file table.
497  *
498  * \param row Pointer to a row in the audio file table.
499  * \param path Result pointer.
500  *
501  * \return Positive on success, negative on errors.
502  */
503 int get_audio_file_path_of_row(const struct osl_row *row, char **path)
504 {
505         struct osl_object path_obj;
506         int ret = osl_get_object(audio_file_table, row, AFTCOL_PATH,
507                 &path_obj);
508         if (ret < 0)
509                 return ret;
510         *path = path_obj.data;
511         return 1;
512 }
513
514 /**
515  * Get the object containing the hash value of an audio file, given a row.
516  *
517  * \param row Pointer to a row of the audio file table.
518  * \param obj Result pointer.
519  *
520  * \return The return value of the underlying call to osl_get_object().
521  *
522  * \sa get_hash_of_row().
523  */
524 static int get_hash_object_of_aft_row(const struct osl_row *row, struct osl_object *obj)
525 {
526         return osl_get_object(audio_file_table, row, AFTCOL_HASH, obj);
527 }
528
529 /**
530  * Get the hash value of an audio file, given a row of the audio file table.
531  *
532  * \param row Pointer to a row of the audio file table.
533  * \param hash Result pointer.
534  *
535  * \a hash points to mapped data and must not be freed by the caller.
536  *
537  * \return The return value of the underlying call to
538  * get_hash_object_of_aft_row().
539  */
540 static int get_hash_of_row(const struct osl_row *row, HASH_TYPE **hash)
541 {
542         struct osl_object obj;
543         int ret = get_hash_object_of_aft_row(row, &obj);
544
545         if (ret < 0)
546                 return ret;
547         *hash = obj.data;
548         return 1;
549 }
550
551 /**
552  * Get the audio format handler info, given a row of the audio file table.
553  *
554  * \param row Pointer to a row of the audio file table.
555  * \param afhi Result pointer.
556  *
557  * \return The return value of the underlying call to osl_get_object().
558  *
559  * \sa get_chunk_table_of_row().
560  */
561 int get_afhi_of_row(const struct osl_row *row, struct audio_format_info *afhi)
562 {
563         struct osl_object obj;
564         int ret = osl_get_object(audio_file_table, row, AFTCOL_AFHI,
565                 &obj);
566         if (ret < 0)
567                 return ret;
568         load_afhi(obj.data, afhi);
569         return 1;
570 }
571
572 /**
573  * Get the chunk table of an audio file, given a row of the audio file table.
574  *
575  * \param row Pointer to a row of the audio file table.
576  * \param afhi Result pointer.
577  *
578  * \return The return value of the underlying call to osl_open_disk_object().
579  *
580  * \sa get_afhi_of_row().
581  */
582 static int get_chunk_table_of_row(const struct osl_row *row, struct audio_format_info *afhi)
583 {
584         struct osl_object obj;
585         int ret = osl_open_disk_object(audio_file_table, row, AFTCOL_CHUNKS,
586                 &obj);
587         if (ret < 0)
588                 return ret;
589         ret = load_chunk_info(&obj, afhi);
590         osl_close_disk_object(&obj);
591         return ret;
592 }
593
594 /**
595  * Mmap the given audio file and update statistics.
596  *
597  * \param aft_row Determines the audio file to be opened and updated.
598  * \param afd Result pointer.
599  *
600  * On success, the numplayed field of the audio file selector info is increased
601  * and the lastplayed time is set to the current time. Finally, the score of
602  * the audio file is updated.
603  *
604  * \return Positive on success, negative on errors.
605  */
606 int open_and_update_audio_file(struct osl_row *aft_row, struct audio_file_data *afd)
607 {
608         HASH_TYPE *aft_hash, file_hash[HASH_SIZE];
609         struct osl_object afsi_obj;
610         struct afs_info new_afsi;
611         int ret = get_hash_of_row(aft_row, &aft_hash);
612
613         if (ret < 0)
614                 return ret;
615         ret = get_audio_file_path_of_row(aft_row, &afd->path);
616         if (ret < 0)
617                 return ret;
618         ret = get_afsi_object_of_row(aft_row, &afsi_obj);
619         if (ret < 0)
620                 return ret;
621         ret = load_afsi(&afd->afsi, &afsi_obj);
622         if (ret < 0)
623                 return ret;
624         ret = get_afhi_of_row(aft_row, &afd->afhi);
625         if (ret < 0)
626                 return ret;
627         ret = get_chunk_table_of_row(aft_row, &afd->afhi);
628         if (ret < 0)
629                 return ret;
630         ret = mmap_full_file(afd->path, O_RDONLY, &afd->map);
631         if (ret < 0)
632                 goto err;
633         hash_function(afd->map.data, afd->map.size, file_hash);
634         ret = -E_HASH_MISMATCH;
635         if (hash_compare(file_hash, aft_hash))
636                 goto err;
637         new_afsi = afd->afsi;
638         new_afsi.num_played++;
639         new_afsi.last_played = time(NULL);
640         save_afsi(&new_afsi, &afsi_obj); /* in-place update */
641         if (afd->current_play_mode == PLAY_MODE_PLAYLIST)
642                 ret = playlist_update_audio_file(aft_row);
643         else
644                 ret = mood_update_audio_file(aft_row, &afd->afsi);
645         return ret;
646 err:
647         free(afd->afhi.chunk_table);
648         return ret;
649 }
650
651 static int get_local_time(uint64_t *seconds, char *buf, size_t size,
652         time_t current_time, enum ls_listing_mode lm)
653 {
654         struct tm t;
655
656         if (!localtime_r((time_t *)seconds, &t))
657                 return -E_LOCALTIME;
658         if (lm == LS_MODE_MBOX) {
659                 if (!strftime(buf, size, "%c", &t))
660                         return -E_STRFTIME;
661                 return 1;
662         }
663         if (*seconds + 6 * 30 * 24 * 3600 > current_time) {
664                 if (!strftime(buf, size, "%b %e %k:%M", &t))
665                         return -E_STRFTIME;
666                 return 1;
667         }
668         if (!strftime(buf, size, "%b %e  %Y", &t))
669                 return -E_STRFTIME;
670         return 1;
671 }
672
673 #define GET_NUM_DIGITS(x, num) { \
674         typeof((x)) _tmp = PARA_ABS(x); \
675         *num = 1; \
676         if ((x)) \
677                 while ((_tmp) > 9) { \
678                         (_tmp) /= 10; \
679                         (*num)++; \
680                 } \
681         }
682
683 static short unsigned get_duration_width(int seconds)
684 {
685         short unsigned width;
686         unsigned hours = seconds / 3600, mins = (seconds % 3600) / 60;
687
688         if (!hours) /* less than one hour => m:ss or mm:ss => 4 or 5 digits */
689                 return 4 + (mins > 9);
690         /* more than one hour => h:mm:ss, hh:mm:ss, hhh:mm:ss, ... */
691         GET_NUM_DIGITS(hours, &width);
692         return width + 6;
693 }
694
695 static void get_duration_buf(int seconds, char *buf, short unsigned max_width)
696 {
697         unsigned hours = seconds / 3600, mins = (seconds % 3600) / 60;
698
699         if (!hours) /* m:ss or mm:ss */
700                 sprintf(buf, "%*u:%02u", max_width - 3, mins, seconds % 60);
701         else /* more than one hour => h:mm:ss, hh:mm:ss, hhh:mm:ss, ... */
702                 sprintf(buf, "%*u:%02u:%02u", max_width - 6, hours, mins,
703                         seconds % 60);
704 }
705
706 static char *make_attribute_line(const char *att_bitmap, struct afs_info *afsi)
707 {
708         char *att_text, *att_line;
709
710         get_attribute_text(&afsi->attributes, " ", &att_text);
711         if (!att_text)
712                 return para_strdup(att_bitmap);
713         att_line = make_message("%s (%s)", att_bitmap, att_text);
714         free(att_text);
715         return att_line;
716 }
717
718 static char *make_lyrics_line(struct afs_info *afsi)
719 {
720         char *lyrics_name;
721
722         lyr_get_name_by_id(afsi->lyrics_id, &lyrics_name);
723         if (!lyrics_name)
724                 return make_message("%u", afsi->lyrics_id);
725         return make_message("%u (%s)", afsi->lyrics_id, lyrics_name);
726 }
727
728 static char *make_image_line(struct afs_info *afsi)
729 {
730         char *image_name;
731         img_get_name_by_id(afsi->image_id, &image_name);
732         if (!image_name)
733                 return make_message("%u", afsi->image_id);
734         return make_message("%u (%s)", afsi->image_id, image_name);
735 }
736
737 static int print_list_item(struct ls_data *d, struct ls_options *opts,
738         struct para_buffer *b, time_t current_time)
739 {
740         int ret;
741         char att_buf[65];
742         char last_played_time[30];
743         char duration_buf[30]; /* nobody has an audio file long enough to overflow this */
744         char score_buf[30] = "";
745         struct afs_info *afsi = &d->afsi;
746         struct audio_format_info *afhi = &d->afhi;
747         struct ls_widths *w = &opts->widths;
748         int have_score = opts->flags & LS_FLAG_ADMISSIBLE_ONLY;
749         char asc_hash[2 * HASH_SIZE + 1];
750         char *att_line, *lyrics_line, *image_line;
751
752         if (opts->mode == LS_MODE_SHORT) {
753                 para_printf(b, "%s\n", d->path);
754                 return 1;
755         }
756         get_attribute_bitmap(&afsi->attributes, att_buf);
757         ret = get_local_time(&afsi->last_played, last_played_time,
758                 sizeof(last_played_time), current_time, opts->mode);
759         if (ret < 0)
760                 return ret;
761         get_duration_buf(afhi->seconds_total, duration_buf, w->duration_width);
762         if (have_score) {
763                 if (opts->mode == LS_MODE_LONG)
764                         sprintf(score_buf, "%*li ", w->score_width, d->score);
765                 else
766                         sprintf(score_buf, "%li ", d->score);
767         }
768
769         PARA_NOTICE_LOG("id: %s, %d\n", d->path, afsi->audio_format_id);
770         if (opts->mode == LS_MODE_LONG) {
771                 para_printf(b,
772                         "%s"    /* score */
773                         "%s "   /* attributes */
774                         "%*d "  /* image_id  */
775                         "%*d "  /* lyrics_id */
776                         "%*d "  /* bitrate */
777                         "%s "   /* audio format */
778                         "%*d "  /* frequency */
779                         "%d "   /* channels */
780                         "%s "   /* duration */
781                         "%*d "  /* num_played */
782                         "%s "   /* last_played */
783                         "%s\n", /* path */
784                         score_buf,
785                         att_buf,
786                         w->image_id_width, afsi->image_id,
787                         w->lyrics_id_width, afsi->lyrics_id,
788                         w->bitrate_width, afhi->bitrate,
789                         audio_format_name(afsi->audio_format_id),
790                         w->frequency_width, afhi->frequency,
791                         afhi->channels,
792                         duration_buf,
793                         w->num_played_width, afsi->num_played,
794                         last_played_time,
795                         d->path
796                 );
797                 return 1;
798         }
799         hash_to_asc(d->hash, asc_hash);
800         att_line = make_attribute_line(att_buf, afsi);
801         lyrics_line = make_lyrics_line(afsi);
802         image_line = make_image_line(afsi);
803         if (opts->mode == LS_MODE_VERBOSE) {
804
805                 para_printf(b,
806                         "%s: %s\n" /* path */
807                         "%s%s%s" /* score */
808                         "attributes: %s\n"
809                         "hash: %s\n"
810                         "image_id: %s\n"
811                         "lyrics_id: %s\n"
812                         "bitrate: %dkbit/s\n"
813                         "format: %s\n"
814                         "frequency: %dHz\n"
815                         "channels: %d\n"
816                         "duration: %s\n"
817                         "num_played: %d\n"
818                         "last_played: %s\n"
819                         "tag info: %s\n",
820                         (opts->flags & LS_FLAG_FULL_PATH)?
821                                 "path" : "file", d->path,
822                         have_score? "score: " : "", score_buf,
823                                 have_score? "\n" : "",
824                         att_line,
825                         asc_hash,
826                         image_line,
827                         lyrics_line,
828                         afhi->bitrate,
829                         audio_format_name(afsi->audio_format_id),
830                         afhi->frequency,
831                         afhi->channels,
832                         duration_buf,
833                         afsi->num_played,
834                         last_played_time,
835                         afhi->info_string
836                 );
837         } else { /* mbox mode */
838                 struct osl_object lyrics_def;
839                 lyr_get_def_by_id(afsi->lyrics_id, &lyrics_def);
840                 para_printf(b,
841                         "From foo@localhost %s\n"
842                         "Received: from\nTo: bar\nFrom: a\n"
843                         "Subject: %s\n\n" /* path */
844                         "%s%s%s" /* score */
845                         "attributes: %s\n"
846                         "hash: %s\n"
847                         "image_id: %s\n"
848                         "lyrics_id: %s\n"
849                         "bitrate: %dkbit/s\n"
850                         "format: %s\n"
851                         "frequency: %dHz\n"
852                         "channels: %d\n"
853                         "duration: %s\n"
854                         "num_played: %d\n"
855                         "tag info: %s\n"
856                         "%s%s\n",
857                         last_played_time,
858                         d->path,
859                         have_score? "score: " : "", score_buf,
860                                 have_score? "\n" : "",
861                         att_line,
862                         asc_hash,
863                         image_line,
864                         lyrics_line,
865                         afhi->bitrate,
866                         audio_format_name(afsi->audio_format_id),
867                         afhi->frequency,
868                         afhi->channels,
869                         duration_buf,
870                         afsi->num_played,
871                         afhi->info_string,
872                         lyrics_def.data? "Lyrics:\n~~~~~~~\n" : "",
873                         lyrics_def.data? (char *)lyrics_def.data : ""
874                 );
875                 if (lyrics_def.data)
876                         osl_close_disk_object(lyrics_def.data);
877         }
878         free(att_line);
879         free(lyrics_line);
880         free(image_line);
881         return 1;
882 }
883
884 static int ls_audio_format_compare(const void *a, const void *b)
885 {
886         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
887         return NUM_COMPARE(d1->afsi.audio_format_id, d2->afsi.audio_format_id);
888 }
889
890 static int ls_duration_compare(const void *a, const void *b)
891 {
892         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
893         return NUM_COMPARE(d1->afhi.seconds_total, d2->afhi.seconds_total);
894 }
895
896 static int ls_bitrate_compare(const void *a, const void *b)
897 {
898         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
899         return NUM_COMPARE(d1->afhi.bitrate, d2->afhi.bitrate);
900 }
901
902 static int ls_lyrics_id_compare(const void *a, const void *b)
903 {
904         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
905         return NUM_COMPARE(d1->afsi.lyrics_id, d2->afsi.lyrics_id);
906 }
907
908 static int ls_image_id_compare(const void *a, const void *b)
909 {
910         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
911         return NUM_COMPARE(d1->afsi.image_id, d2->afsi.image_id);
912 }
913
914 static int ls_channels_compare(const void *a, const void *b)
915 {
916         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
917         return NUM_COMPARE(d1->afhi.channels, d2->afhi.channels);
918 }
919
920 static int ls_frequency_compare(const void *a, const void *b)
921 {
922         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
923         return NUM_COMPARE(d1->afhi.frequency, d2->afhi.frequency);
924 }
925
926 static int ls_num_played_compare(const void *a, const void *b)
927 {
928         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
929         return NUM_COMPARE(d1->afsi.num_played, d2->afsi.num_played);
930 }
931
932 static int ls_last_played_compare(const void *a, const void *b)
933 {
934         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
935         return NUM_COMPARE(d1->afsi.last_played, d2->afsi.last_played);
936 }
937
938 static int ls_score_compare(const void *a, const void *b)
939 {
940         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
941         return NUM_COMPARE(d1->score, d2->score);
942 }
943
944 static int ls_path_compare(const void *a, const void *b)
945 {
946         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
947         return strcmp(d1->path, d2->path);
948 }
949
950 static int sort_matching_paths(struct ls_options *options)
951 {
952         size_t nmemb = options->num_matching_paths;
953         size_t size = sizeof(*options->data_ptr);
954         int (*compar)(const void *, const void *);
955         int i;
956
957         options->data_ptr = para_malloc(nmemb * sizeof(*options->data_ptr));
958         for (i = 0; i < nmemb; i++)
959                 options->data_ptr[i] = options->data + i;
960
961         /* In these cases the array is already sorted */
962         if (options->sorting == LS_SORT_BY_PATH
963                 && !(options->flags & LS_FLAG_ADMISSIBLE_ONLY)
964                 && (options->flags & LS_FLAG_FULL_PATH))
965                 return 1;
966         if (options->sorting == LS_SORT_BY_SCORE &&
967                         options->flags & LS_FLAG_ADMISSIBLE_ONLY)
968                 return 1;
969
970         switch (options->sorting) {
971         case LS_SORT_BY_PATH:
972                 compar = ls_path_compare; break;
973         case LS_SORT_BY_SCORE:
974                 compar = ls_score_compare; break;
975         case LS_SORT_BY_LAST_PLAYED:
976                 compar = ls_last_played_compare; break;
977         case LS_SORT_BY_NUM_PLAYED:
978                 compar = ls_num_played_compare; break;
979         case LS_SORT_BY_FREQUENCY:
980                 compar = ls_frequency_compare; break;
981         case LS_SORT_BY_CHANNELS:
982                 compar = ls_channels_compare; break;
983         case LS_SORT_BY_IMAGE_ID:
984                 compar = ls_image_id_compare; break;
985         case LS_SORT_BY_LYRICS_ID:
986                 compar = ls_lyrics_id_compare; break;
987         case LS_SORT_BY_BITRATE:
988                 compar = ls_bitrate_compare; break;
989         case LS_SORT_BY_DURATION:
990                 compar = ls_duration_compare; break;
991         case LS_SORT_BY_AUDIO_FORMAT:
992                 compar = ls_audio_format_compare; break;
993         default:
994                 return -E_BAD_SORT;
995         }
996         qsort(options->data_ptr, nmemb, size, compar);
997         return 1;
998 }
999
1000 /* row is either an aft_row or a row of the score table */
1001 /* TODO: Only compute widths if we need them */
1002 static int prepare_ls_row(struct osl_row *row, void *ls_opts)
1003 {
1004         int ret, i;
1005         struct ls_options *options = ls_opts;
1006         struct ls_data *d;
1007         struct ls_widths *w;
1008         unsigned short num_digits;
1009         unsigned tmp;
1010         struct osl_row *aft_row;
1011         long score;
1012         char *path;
1013
1014         if (options->flags & LS_FLAG_ADMISSIBLE_ONLY) {
1015                 ret = get_score_and_aft_row(row, &score, &aft_row);
1016                 if (ret < 0)
1017                         return ret;
1018         } else
1019                 aft_row = row;
1020         ret = get_audio_file_path_of_row(aft_row, &path);
1021         if (ret < 0)
1022                 return ret;
1023         if (!(options->flags & LS_FLAG_FULL_PATH)) {
1024                 char *p = strrchr(path, '/');
1025                 if (p)
1026                         path = p + 1;
1027         }
1028         if (options->num_patterns) {
1029                 for (i = 0; i < options->num_patterns; i++) {
1030                         ret = fnmatch(options->patterns[i], path, 0);
1031                         if (!ret)
1032                                 break;
1033                         if (ret == FNM_NOMATCH)
1034                                 continue;
1035                         return -E_FNMATCH;
1036                 }
1037                 if (i >= options->num_patterns) /* no match */
1038                         return 1;
1039         }
1040         tmp = options->num_matching_paths++;
1041         if (options->num_matching_paths > options->array_size) {
1042                 options->array_size++;
1043                 options->array_size *= 2;
1044                 options->data = para_realloc(options->data, options->array_size
1045                         * sizeof(*options->data));
1046         }
1047         d = options->data + tmp;
1048         ret = get_afsi_of_row(aft_row, &d->afsi);
1049         if (ret < 0)
1050                 return ret;
1051         ret = get_afhi_of_row(aft_row, &d->afhi);
1052         if (ret < 0)
1053                 return ret;
1054         d->path = path;
1055         ret = get_hash_of_row(aft_row, &d->hash);
1056         if (ret < 0)
1057                 return ret;
1058         w = &options->widths;
1059         GET_NUM_DIGITS(d->afsi.image_id, &num_digits);
1060         w->image_id_width = PARA_MAX(w->image_id_width, num_digits);
1061         GET_NUM_DIGITS(d->afsi.lyrics_id, &num_digits);
1062         w->lyrics_id_width = PARA_MAX(w->lyrics_id_width, num_digits);
1063         GET_NUM_DIGITS(d->afhi.bitrate, &num_digits);
1064         w->bitrate_width = PARA_MAX(w->bitrate_width, num_digits);
1065         GET_NUM_DIGITS(d->afhi.frequency, &num_digits);
1066         w->frequency_width = PARA_MAX(w->frequency_width, num_digits);
1067         GET_NUM_DIGITS(d->afsi.num_played, &num_digits);
1068         w->num_played_width = PARA_MAX(w->num_played_width, num_digits);
1069         /* get the number of chars to print this amount of time */
1070         tmp = get_duration_width(d->afhi.seconds_total);
1071         w->duration_width = PARA_MAX(w->duration_width, tmp);
1072         if (options->flags & LS_FLAG_ADMISSIBLE_ONLY) {
1073                 GET_NUM_DIGITS(score, &num_digits);
1074                 num_digits++; /* add one for the sign (space or "-") */
1075                 w->score_width = PARA_MAX(w->score_width, num_digits);
1076                 d->score = score;
1077         }
1078         return 1;
1079 }
1080
1081 static int com_ls_callback(const struct osl_object *query,
1082                 struct osl_object *ls_output)
1083 {
1084         struct ls_options *opts = query->data;
1085         char *p, *pattern_start = (char *)query->data + sizeof(*opts);
1086         struct para_buffer b = {.buf = NULL, .size = 0};
1087         int i = 0, ret;
1088         time_t current_time;
1089
1090
1091         PARA_NOTICE_LOG("%d patterns\n", opts->num_patterns);
1092         if (opts->num_patterns) {
1093                 opts->patterns = para_malloc(opts->num_patterns * sizeof(char *));
1094                 for (i = 0, p = pattern_start; i < opts->num_patterns; i++) {
1095                         opts->patterns[i] = p;
1096                         p += strlen(p) + 1;
1097                         PARA_NOTICE_LOG("pattern %d: %s\n", i, opts->patterns[i]);
1098                 }
1099         } else
1100                 opts->patterns = NULL;
1101         if (opts->flags & LS_FLAG_ADMISSIBLE_ONLY)
1102                 ret = admissible_file_loop(opts, prepare_ls_row);
1103         else
1104                 ret = osl_rbtree_loop(audio_file_table, AFTCOL_PATH, opts,
1105                         prepare_ls_row);
1106         if (ret < 0)
1107                 goto out;
1108         ret = opts->num_patterns? -E_NO_MATCH : 0;
1109         if (!opts->num_matching_paths) {
1110                 PARA_NOTICE_LOG("no match, ret: %d\n", ret);
1111                 goto out;
1112         }
1113         ret = sort_matching_paths(opts);
1114         if (ret < 0)
1115                 goto out;
1116         time(&current_time);
1117         if (opts->flags & LS_FLAG_REVERSE)
1118                 for (i = opts->num_matching_paths - 1; i >= 0; i--) {
1119                         ret = print_list_item(opts->data_ptr[i], opts, &b, current_time);
1120                         if (ret < 0)
1121                                 break;
1122                 }
1123         else
1124                 for (i = 0; i < opts->num_matching_paths; i++) {
1125                         ret = print_list_item(opts->data_ptr[i], opts, &b, current_time);
1126                         if (ret < 0)
1127                                 break;
1128                 }
1129         ret = 1;
1130 out:
1131         ls_output->data = b.buf;
1132         PARA_NOTICE_LOG("ls_outoute.data: %p\n", ls_output->data);
1133         ls_output->size = b.size;
1134         free(opts->data);
1135         free(opts->data_ptr);
1136         free(opts->patterns);
1137         return ret;
1138 }
1139
1140 /*
1141  * TODO: flags -h (sort by hash) -lm (list in mbox format)
1142  *
1143  * long list: list hash, attributes as (xx--x-x-), file size, lastplayed
1144  * full list: list everything, including afsi, afhi, atts as clear text
1145  *
1146  * */
1147 int com_afs_ls(int fd, int argc, char * const * const argv)
1148 {
1149         int i, ret;
1150         unsigned flags = 0;
1151         enum ls_sorting_method sort = LS_SORT_BY_PATH;
1152         enum ls_listing_mode mode = LS_MODE_SHORT;
1153         struct ls_options opts = {.patterns = NULL};
1154         struct osl_object query = {.data = &opts, .size = sizeof(opts)},
1155                 ls_output;
1156
1157         for (i = 1; i < argc; i++) {
1158                 const char *arg = argv[i];
1159                 if (arg[0] != '-')
1160                         break;
1161                 if (!strcmp(arg, "--")) {
1162                         i++;
1163                         break;
1164                 }
1165                 if (!strncmp(arg, "-l", 2)) {
1166                         if (!*(arg + 2)) {
1167                                 mode = LS_MODE_LONG;
1168                                 continue;
1169                         }
1170                         if (*(arg + 3))
1171                                 return -E_AFT_SYNTAX;
1172                         switch(*(arg + 2)) {
1173                         case 's':
1174                                 mode = LS_MODE_SHORT;
1175                                 continue;
1176                         case 'l':
1177                                 mode = LS_MODE_LONG;
1178                                 continue;
1179                         case 'v':
1180                                 mode = LS_MODE_VERBOSE;
1181                                 continue;
1182                         case 'm':
1183                                 mode = LS_MODE_MBOX;
1184                                 continue;
1185                         default:
1186                                 return -E_AFT_SYNTAX;
1187                         }
1188                 }
1189                 if (!strcmp(arg, "-p")) {
1190                         flags |= LS_FLAG_FULL_PATH;
1191                         continue;
1192                 }
1193                 if (!strcmp(arg, "-a")) {
1194                         flags |= LS_FLAG_ADMISSIBLE_ONLY;
1195                         continue;
1196                 }
1197                 if (!strcmp(arg, "-r")) {
1198                         flags |= LS_FLAG_REVERSE;
1199                         continue;
1200                 }
1201                 if (!strncmp(arg, "-s", 2)) {
1202                         if (!*(arg + 2) || *(arg + 3))
1203                                 return -E_AFT_SYNTAX;
1204                         switch(*(arg + 2)) {
1205                         case 'p':
1206                                 sort = LS_SORT_BY_PATH;
1207                                 continue;
1208                         case 's': /* -ss implies -a */
1209                                 sort = LS_SORT_BY_SCORE;
1210                                 flags |= LS_FLAG_ADMISSIBLE_ONLY;
1211                                 continue;
1212                         case 'l':
1213                                 sort = LS_SORT_BY_LAST_PLAYED;
1214                                 continue;
1215                         case 'n':
1216                                 sort = LS_SORT_BY_NUM_PLAYED;
1217                                 continue;
1218                         case 'f':
1219                                 sort = LS_SORT_BY_FREQUENCY;
1220                                 continue;
1221                         case 'c':
1222                                 sort = LS_SORT_BY_CHANNELS;
1223                                 continue;
1224                         case 'i':
1225                                 sort = LS_SORT_BY_IMAGE_ID;
1226                                 continue;
1227                         case 'y':
1228                                 sort = LS_SORT_BY_LYRICS_ID;
1229                                 continue;
1230                         case 'b':
1231                                 sort = LS_SORT_BY_BITRATE;
1232                                 continue;
1233                         case 'd':
1234                                 sort = LS_SORT_BY_DURATION;
1235                                 continue;
1236                         case 'a':
1237                                 sort = LS_SORT_BY_AUDIO_FORMAT;
1238                                 continue;
1239                         default:
1240                                 return -E_AFT_SYNTAX;
1241                         }
1242                 }
1243                 return -E_AFT_SYNTAX;
1244         }
1245         opts.flags = flags;
1246         opts.sorting = sort;
1247         opts.mode = mode;
1248         opts.num_patterns = argc - i;
1249         ret = send_option_arg_callback_request(&query, opts.num_patterns,
1250                 argv + i, com_ls_callback, &ls_output);
1251         if (ret > 0) {
1252                 ret = send_buffer(fd, (char *)ls_output.data);
1253                 free(ls_output.data);
1254         }
1255         return ret;
1256 }
1257
1258 /**
1259  * Call the given function for each file in the audio file table.
1260  *
1261  * \param private_data An arbitrary data pointer, passed to \a func.
1262  * \param func The custom function to be called.
1263  *
1264  * \return The return value of the underlying call to osl_rbtree_loop().
1265  */
1266 int audio_file_loop(void *private_data, osl_rbtree_loop_func *func)
1267 {
1268         return osl_rbtree_loop(audio_file_table, AFTCOL_HASH, private_data,
1269                 func);
1270 }
1271
1272 static struct osl_row *find_hash_sister(HASH_TYPE *hash)
1273 {
1274         const struct osl_object obj = {.data = hash, .size = HASH_SIZE};
1275         struct osl_row *row;
1276
1277         osl_get_row(audio_file_table, AFTCOL_HASH, &obj, &row);
1278         return row;
1279 }
1280
1281 enum aft_row_offsets {
1282         AFTROW_AFHI_OFFSET_POS = 0,
1283         AFTROW_CHUNKS_OFFSET_POS = 2,
1284         AFTROW_AUDIO_FORMAT_OFFSET = 4,
1285         AFTROW_FLAGS_OFFSET = 5,
1286         AFTROW_HASH_OFFSET = 9,
1287         AFTROW_PATH_OFFSET = (AFTROW_HASH_OFFSET + HASH_SIZE),
1288 };
1289
1290 /* never save the afsi, as the server knows it too. Note that afhi might be NULL.
1291  * In this case, afhi won't be stored in the buffer  */
1292 static void save_audio_file_info(HASH_TYPE *hash, const char *path,
1293                 struct audio_format_info *afhi, uint32_t flags,
1294                 uint8_t audio_format_num, struct osl_object *obj)
1295 {
1296         size_t path_len = strlen(path) + 1;
1297         size_t afhi_size = sizeof_afhi_buf(afhi);
1298         size_t size = AFTROW_PATH_OFFSET + path_len + afhi_size
1299                 + sizeof_chunk_info_buf(afhi);
1300         char *buf = para_malloc(size);
1301         uint16_t pos;
1302
1303         write_u8(buf + AFTROW_AUDIO_FORMAT_OFFSET, audio_format_num);
1304         write_u32(buf + AFTROW_FLAGS_OFFSET, flags);
1305
1306         memcpy(buf + AFTROW_HASH_OFFSET, hash, HASH_SIZE);
1307         strcpy(buf + AFTROW_PATH_OFFSET, path);
1308
1309         pos = AFTROW_PATH_OFFSET + path_len;
1310         PARA_DEBUG_LOG("size: %zu, afhi starts at %d\n", size, pos);
1311         PARA_DEBUG_LOG("last afhi byte: %p, pos %zu\n", buf + pos + afhi_size - 1,
1312                 pos + afhi_size - 1);
1313         write_u16(buf + AFTROW_AFHI_OFFSET_POS, pos);
1314         save_afhi(afhi, buf + pos);
1315
1316         pos += afhi_size;
1317         PARA_DEBUG_LOG("size: %zu, chunks start at %d\n", size, pos);
1318         write_u16(buf + AFTROW_CHUNKS_OFFSET_POS, pos);
1319         save_chunk_info(afhi, buf + pos);
1320         PARA_DEBUG_LOG("last byte in buf: %p\n", buf + size - 1);
1321         obj->data = buf;
1322         obj->size = size;
1323 }
1324
1325 /*
1326 input:
1327 ~~~~~~
1328 HS:     hash sister
1329 PB:     path brother
1330 F:      force flag given
1331
1332 output:
1333 ~~~~~~~
1334 AFHI:   whether afhi and chunk table are computed and sent
1335 ACTION: table modifications to be performed
1336
1337 +---+----+-----+------+---------------------------------------------------+
1338 | HS | PB | F  | AFHI | ACTION
1339 +---+----+-----+------+---------------------------------------------------+
1340 | Y |  Y |  Y  |  Y   | if HS != PB: remove PB. HS: force afhi update,
1341 |                     | update path, keep afsi
1342 +---+----+-----+------+---------------------------------------------------+
1343 | Y |  Y |  N  |  N   | if HS == PB: do not send callback request at all.
1344 |                     | otherwise: remove PB, HS: update path, keep afhi,
1345 |                     | afsi.
1346 +---+----+-----+------+---------------------------------------------------+
1347 | Y |  N |  Y  |  Y   | (rename) force afhi update of HS, update path of
1348 |                     | HS, keep afsi
1349 +---+----+-----+------+---------------------------------------------------+
1350 | Y |  N |  N  |  N   | (file rename) update path of HS, keep afsi, afhi
1351 +---+----+-----+------+---------------------------------------------------+
1352 | N |  Y |  Y  |  Y   | (file change) update afhi, hash, of PB, keep afsi
1353 |                     | (force has no effect)
1354 +---+----+-----+------+---------------------------------------------------+
1355 | N |  Y |  N  |  Y   | (file change) update afhi, hash of PB, keep afsi
1356 +---+----+-----+------+---------------------------------------------------+
1357 | N |  N |  Y  |  Y   | (new file) create new entry (force has no effect)
1358 +---+----+-----+------+---------------------------------------------------+
1359 | N |  N |  N  |  Y   | (new file) create new entry
1360 +---+----+-----+------+---------------------------------------------------+
1361
1362 afhi <=> force or no HS
1363
1364 */
1365
1366
1367 #define ADD_FLAG_LAZY 1
1368 #define ADD_FLAG_FORCE 2
1369 #define ADD_FLAG_VERBOSE 4
1370 #define ADD_FLAG_ALL 8
1371
1372 /* TODO: change log messages so that they get written to the result buffer */
1373
1374 static int com_add_callback(const struct osl_object *query,
1375                 __a_unused struct osl_object *result)
1376 {
1377         char *buf = query->data, *path;
1378         struct osl_row *pb, *aft_row;
1379         const struct osl_row *hs;
1380         struct osl_object objs[NUM_AFT_COLUMNS];
1381         HASH_TYPE *hash;
1382         char asc[2 * HASH_SIZE + 1];
1383         int ret;
1384         char afsi_buf[AFSI_SIZE];
1385         uint32_t flags = read_u32(buf + AFTROW_FLAGS_OFFSET);
1386         struct afs_info default_afsi = {.last_played = 0};
1387
1388         hash = (HASH_TYPE *)buf + AFTROW_HASH_OFFSET;
1389         hash_to_asc(hash, asc);;
1390         objs[AFTCOL_HASH].data = buf + AFTROW_HASH_OFFSET;
1391         objs[AFTCOL_HASH].size = HASH_SIZE;
1392
1393         path = buf + AFTROW_PATH_OFFSET;
1394         objs[AFTCOL_PATH].data = path;
1395         objs[AFTCOL_PATH].size = strlen(path) + 1;
1396
1397         PARA_INFO_LOG("request to add %s\n", path);
1398         hs = find_hash_sister(hash);
1399         ret = aft_get_row_of_path(path, &pb);
1400         if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1401                 return ret;
1402         if (hs && pb && hs == pb && !(flags & ADD_FLAG_FORCE)) {
1403                 if (flags & ADD_FLAG_VERBOSE)
1404                         PARA_NOTICE_LOG("ignoring duplicate %p\n", path);
1405                 return 1;
1406         }
1407         if (hs && hs != pb) {
1408                 struct osl_object obj;
1409                 if (pb) { /* hs trumps pb, remove pb */
1410                         if (flags & ADD_FLAG_VERBOSE)
1411                                 PARA_NOTICE_LOG("removing path brother\n");
1412                         ret = osl_del_row(audio_file_table, pb);
1413                         if (ret < 0)
1414                                 return ret;
1415                         pb = NULL;
1416                 }
1417                 /* file rename, update hs' path */
1418                 ret = osl_get_object(audio_file_table, hs, AFTCOL_PATH, &obj);
1419                 if (flags & ADD_FLAG_VERBOSE)
1420                         PARA_NOTICE_LOG("rename %s -> %s\n", (char *)obj.data, path);
1421                 ret = osl_update_object(audio_file_table, hs, AFTCOL_PATH,
1422                         &objs[AFTCOL_PATH]);
1423                 if (ret < 0)
1424                         return ret;
1425                 if (!(flags & ADD_FLAG_FORCE))
1426                         return ret;
1427         }
1428         /* no hs or force mode, child must have sent afhi */
1429         uint16_t afhi_offset = read_u16(buf + AFTROW_AFHI_OFFSET_POS);
1430         uint16_t chunks_offset = read_u16(buf + AFTROW_CHUNKS_OFFSET_POS);
1431
1432         objs[AFTCOL_AFHI].data = buf + afhi_offset;
1433         objs[AFTCOL_AFHI].size = chunks_offset - afhi_offset;
1434         if (!objs[AFTCOL_AFHI].size) /* "impossible" */
1435                 return -E_NO_AFHI;
1436         objs[AFTCOL_CHUNKS].data = buf + chunks_offset;
1437         objs[AFTCOL_CHUNKS].size = query->size - chunks_offset;
1438         if (pb && !hs) { /* update pb's hash */
1439                 char old_asc[2 * HASH_SIZE + 1];
1440                 HASH_TYPE *old_hash;
1441                 ret = get_hash_of_row(pb, &old_hash);
1442                 if (ret < 0)
1443                         return ret;
1444                 hash_to_asc(old_hash, old_asc);
1445                 if (flags & ADD_FLAG_VERBOSE)
1446                         PARA_NOTICE_LOG("file change: %s %s -> %s\n", path,
1447                                 old_asc, asc);
1448                 ret = osl_update_object(audio_file_table, pb, AFTCOL_HASH,
1449                         &objs[AFTCOL_HASH]);
1450                 if (ret < 0)
1451                         return ret;
1452         }
1453         if (hs || pb) { /* (hs != NULL and pb != NULL) implies hs == pb */
1454                 const struct osl_row *row = pb? pb : hs;
1455                 /* update afhi and chunk_table */
1456                 if (flags & ADD_FLAG_VERBOSE)
1457                         PARA_DEBUG_LOG("updating audio format handler info (%zd bytes)\n",
1458                                 objs[AFTCOL_AFHI].size);
1459                 ret = osl_update_object(audio_file_table, row, AFTCOL_AFHI,
1460                         &objs[AFTCOL_AFHI]);
1461                 if (ret < 0)
1462                         return ret;
1463                 if (flags & ADD_FLAG_VERBOSE)
1464                         PARA_DEBUG_LOG("updating chunk table\n");
1465                 ret = osl_update_object(audio_file_table, row, AFTCOL_CHUNKS,
1466                         &objs[AFTCOL_CHUNKS]);
1467                 if (ret < 0)
1468                         return ret;
1469                 return mood_update_audio_file(row, NULL);
1470         }
1471         /* new entry, use default afsi */
1472         default_afsi.last_played = time(NULL) - 365 * 24 * 60 * 60;
1473         default_afsi.audio_format_id = read_u8(buf + AFTROW_AUDIO_FORMAT_OFFSET);
1474
1475         objs[AFTCOL_AFSI].data = &afsi_buf;
1476         objs[AFTCOL_AFSI].size = AFSI_SIZE;
1477         save_afsi(&default_afsi, &objs[AFTCOL_AFSI]);
1478         ret = osl_add_and_get_row(audio_file_table, objs, &aft_row);
1479         if (ret < 0)
1480                 return ret;
1481         return mood_update_audio_file(aft_row, NULL);
1482 }
1483
1484 struct private_add_data {
1485         int fd;
1486         uint32_t flags;
1487 };
1488
1489 static int path_brother_callback(const struct osl_object *query,
1490                 struct osl_object *result)
1491 {
1492         char *path = query->data;
1493         struct osl_row *path_brother;
1494         int ret = aft_get_row_of_path(path, &path_brother);
1495         if (ret < 0)
1496                 return ret;
1497         result->data = para_malloc(sizeof(path_brother));
1498         result->size = sizeof(path_brother);
1499         *(struct osl_row **)(result->data) = path_brother;
1500         return 1;
1501 }
1502
1503 static int hash_sister_callback(const struct osl_object *query,
1504                 struct osl_object *result)
1505 {
1506         HASH_TYPE *hash = query->data;
1507         struct osl_row *hash_sister;
1508
1509         hash_sister = find_hash_sister(hash);
1510         if (!hash_sister)
1511                 return -E_RB_KEY_NOT_FOUND;
1512         result->data = para_malloc(sizeof(hash_sister));
1513         result->size = sizeof(hash_sister);
1514         *(struct osl_row **)(result->data) = hash_sister;
1515         return 1;
1516 }
1517
1518 static int add_one_audio_file(const char *path, const void *private_data)
1519 {
1520         int ret;
1521         uint8_t format_num = -1;
1522         const struct private_add_data *pad = private_data;
1523         struct audio_format_info afhi, *afhi_ptr = NULL;
1524         struct osl_row *pb = NULL, *hs = NULL; /* path brother/hash sister */
1525         struct osl_object map, obj = {.data = NULL}, query, result;
1526         HASH_TYPE hash[HASH_SIZE];
1527
1528         afhi.header_offset = 0;
1529         afhi.header_len = 0;
1530         ret = guess_audio_format(path);
1531         if (ret < 0 && !(pad->flags & ADD_FLAG_ALL)) {
1532                 if (pad->flags & ADD_FLAG_VERBOSE)
1533                         ret = send_va_buffer(pad->fd, "%s: %s\n",
1534                                 PARA_STRERROR(-ret), path);
1535                 ret = 1;
1536                 goto out_free;
1537         }
1538         query.data = (char *)path;
1539         query.size = strlen(path) + 1;
1540         ret = send_callback_request(path_brother_callback, &query, &result);
1541         if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1542                 goto out_free;
1543         if (ret >= 0) {
1544                 pb = *(struct osl_row **)result.data;
1545                 free(result.data);
1546         }
1547         ret = 1;
1548         if (pb && (pad->flags & ADD_FLAG_LAZY)) { /* lazy is really cheap */
1549                 if (pad->flags & ADD_FLAG_VERBOSE)
1550                         ret = send_va_buffer(pad->fd, "lazy-ignore: %s\n", path);
1551                 goto out_free;
1552         }
1553         /* We still want to add this file. Compute its hash. */
1554         ret = mmap_full_file(path, O_RDONLY, &map);
1555         if (ret < 0)
1556                 goto out_free;
1557         hash_function(map.data, map.size, hash);
1558
1559         /* Check whether database contains file with the same hash. */
1560         query.data = hash;
1561         query.size = HASH_SIZE;
1562         ret = send_callback_request(hash_sister_callback, &query, &result);
1563         if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1564                 goto out_free;
1565         if (ret >= 0) {
1566                 hs = *(struct osl_row **)result.data;
1567                 free(result.data);
1568         }
1569         /* Return success if we already know this file. */
1570         ret = 1;
1571         if (pb && hs && hs == pb && (!(pad->flags & ADD_FLAG_FORCE))) {
1572                 if (pad->flags & ADD_FLAG_VERBOSE)
1573                         ret = send_va_buffer(pad->fd,
1574                                 "not forcing update: %s\n", path);
1575                 goto out_unmap;
1576         }
1577         /*
1578          * we won't recalculate the audio format info and the chunk table if
1579          * there is a hash sister unless in FORCE mode.
1580          */
1581         if (!hs || (pad->flags & ADD_FLAG_FORCE)) {
1582                 ret = compute_afhi(path, map.data, map.size, &afhi);
1583                 if (ret < 0)
1584                         goto out_unmap;
1585                 format_num = ret;
1586                 afhi_ptr = &afhi;
1587         }
1588         if (pad->flags & ADD_FLAG_VERBOSE) {
1589                 ret = send_va_buffer(pad->fd, "adding %s\n", path);
1590                 if (ret < 0)
1591                         goto out_unmap;
1592         }
1593         munmap(map.data, map.size);
1594         save_audio_file_info(hash, path, afhi_ptr, pad->flags, format_num, &obj);
1595         /* Ask afs to consider this entry for adding. */
1596         ret = send_callback_request(com_add_callback, &obj, NULL);
1597         goto out_free;
1598
1599 out_unmap:
1600         munmap(map.data, map.size);
1601 out_free:
1602         if (ret < 0 && ret != -E_SEND)
1603                 send_va_buffer(pad->fd, "failed to add %s (%s)\n", path,
1604                         PARA_STRERROR(-ret));
1605         free(obj.data);
1606         if (afhi_ptr)
1607                 free(afhi_ptr->chunk_table);
1608         /* it's not an error if not all files could be added */
1609         return ret == -E_SEND? ret : 1;
1610 }
1611
1612 int com_add(int fd, int argc, char * const * const argv)
1613 {
1614         int i, ret;
1615         struct private_add_data pad = {.fd = fd, .flags = 0};
1616         struct stat statbuf;
1617
1618         for (i = 1; i < argc; i++) {
1619                 const char *arg = argv[i];
1620                 if (arg[0] != '-')
1621                         break;
1622                 if (!strcmp(arg, "--")) {
1623                         i++;
1624                         break;
1625                 }
1626                 if (!strcmp(arg, "-a")) {
1627                         pad.flags |= ADD_FLAG_ALL;
1628                         continue;
1629                 }
1630                 if (!strcmp(arg, "-l")) {
1631                         pad.flags |= ADD_FLAG_LAZY;
1632                         continue;
1633                 }
1634                 if (!strcmp(arg, "-f")) {
1635                         pad.flags |= ADD_FLAG_FORCE;
1636                         continue;
1637                 }
1638                 if (!strcmp(arg, "-v")) {
1639                         pad.flags |= ADD_FLAG_VERBOSE;
1640                         continue;
1641                 }
1642         }
1643         if (argc <= i)
1644                 return -E_AFT_SYNTAX;
1645         for (; i < argc; i++) {
1646                 char *path;
1647                 ret = verify_path(argv[i], &path);
1648                 if (ret < 0) {
1649                         ret = send_va_buffer(fd, "%s: %s\n", argv[i], PARA_STRERROR(-ret));
1650                         if (ret < 0)
1651                                 return ret;
1652                         continue;
1653                 }
1654                 ret = stat(path, &statbuf);
1655                 if (ret < 0) {
1656                         ret = send_va_buffer(fd, "failed to stat %s (%s)\n", path,
1657                                 strerror(errno));
1658                         free(path);
1659                         if (ret < 0)
1660                                 return ret;
1661                         continue;
1662                 }
1663                 if (S_ISDIR(statbuf.st_mode))
1664                         ret = for_each_file_in_dir(path, add_one_audio_file,
1665                                 &pad);
1666                 else
1667                         ret = add_one_audio_file(path, &pad);
1668                 if (ret < 0) {
1669                         send_va_buffer(fd, "%s: %s\n", path, PARA_STRERROR(-ret));
1670                         free(path);
1671                         return ret;
1672                 }
1673                 free(path);
1674         }
1675         return 1;
1676
1677 }
1678
1679 enum touch_flags {
1680         TOUCH_FLAG_FNM_PATHNAME = 1,
1681         TOUCH_FLAG_VERBOSE = 2
1682 };
1683
1684 struct com_touch_options {
1685         int32_t num_played;
1686         int64_t last_played;
1687         int32_t lyrics_id;
1688         int32_t image_id;
1689         unsigned flags;
1690 };
1691
1692 struct touch_action_data {
1693         struct com_touch_options *cto;
1694         struct para_buffer pb;
1695 };
1696
1697 static int touch_audio_file(__a_unused struct osl_table *table,
1698                 struct osl_row *row, const char *name, void *data)
1699 {
1700         struct touch_action_data *tad = data;
1701         struct osl_object obj;
1702         struct afs_info old_afsi, new_afsi;
1703         int ret, no_options = tad->cto->num_played < 0 && tad->cto->last_played < 0 &&
1704                 tad->cto->lyrics_id < 0 && tad->cto->image_id < 0;
1705
1706         ret = get_afsi_object_of_row(row, &obj);
1707         if (ret < 0) {
1708                 para_printf(&tad->pb, "%s: %s\n", name, PARA_STRERROR(-ret));
1709                 return 1;
1710         }
1711         ret = load_afsi(&old_afsi, &obj);
1712         if (ret < 0) {
1713                 para_printf(&tad->pb, "%s: %s\n", name, PARA_STRERROR(-ret));
1714                 return 1;
1715         }
1716         new_afsi = old_afsi;
1717         if (no_options) {
1718                 new_afsi.num_played++;
1719                 new_afsi.last_played = time(NULL);
1720                 if (tad->cto->flags & TOUCH_FLAG_VERBOSE)
1721                         para_printf(&tad->pb, "%s: num_played = %u, "
1722                                 "last_played = now()\n", name,
1723                                 new_afsi.num_played);
1724         } else {
1725                 if (tad->cto->flags & TOUCH_FLAG_VERBOSE)
1726                         para_printf(&tad->pb, "touching %s\n", name);
1727                 if (tad->cto->lyrics_id >= 0)
1728                         new_afsi.lyrics_id = tad->cto->lyrics_id;
1729                 if (tad->cto->image_id >= 0)
1730                         new_afsi.image_id = tad->cto->image_id;
1731                 if (tad->cto->num_played >= 0)
1732                         new_afsi.num_played = tad->cto->num_played;
1733                 if (tad->cto->last_played >= 0)
1734                         new_afsi.last_played = tad->cto->last_played;
1735         }
1736         save_afsi(&new_afsi, &obj); /* in-place update */
1737         ret = mood_update_audio_file(row, &old_afsi);
1738         if (ret < 0)
1739                 para_printf(&tad->pb, "%s: %s\n", name, PARA_STRERROR(-ret));
1740         return 1;
1741 }
1742
1743 static int com_touch_callback(const struct osl_object *query,
1744                 struct osl_object *result)
1745 {
1746         struct touch_action_data tad = {.cto = query->data};
1747         int ret;
1748         struct pattern_match_data pmd = {
1749                 .table = audio_file_table,
1750                 .loop_col_num = AFTCOL_HASH,
1751                 .match_col_num = AFTCOL_PATH,
1752                 .patterns = {.data = (char *)query->data + sizeof(*tad.cto),
1753                         .size = query->size - sizeof(*tad.cto)},
1754                 .data = &tad,
1755                 .action = touch_audio_file
1756         };
1757         if (tad.cto->flags & TOUCH_FLAG_FNM_PATHNAME)
1758                 pmd.fnmatch_flags |= FNM_PATHNAME;
1759         ret = for_each_matching_row(&pmd);
1760         if (ret < 0)
1761                 para_printf(&tad.pb, "%s\n", PARA_STRERROR(-ret));
1762         if (tad.pb.buf) {
1763                 result->data = tad.pb.buf;
1764                 result->size = tad.pb.size;
1765                 return 1;
1766         }
1767         return ret < 0? ret : 0;
1768 }
1769
1770 int com_touch(int fd, int argc, char * const * const argv)
1771 {
1772         struct com_touch_options cto = {
1773                 .num_played = -1,
1774                 .last_played = -1,
1775                 .lyrics_id = -1,
1776                 .image_id = -1
1777         };
1778         struct osl_object query = {.data = &cto, .size = sizeof(cto)},
1779                 result;
1780         int i, ret;
1781
1782
1783         for (i = 1; i < argc; i++) {
1784                 const char *arg = argv[i];
1785                 if (arg[0] != '-')
1786                         break;
1787                 if (!strcmp(arg, "--")) {
1788                         i++;
1789                         break;
1790                 }
1791                 if (!strncmp(arg, "-n", 2)) {
1792                         ret = para_atoi32(arg + 2, &cto.num_played);
1793                         if (ret < 0)
1794                                 return ret;
1795                         continue;
1796                 }
1797                 if (!strncmp(arg, "-l", 2)) {
1798                         ret = para_atoi64(arg + 2, &cto.last_played);
1799                         if (ret < 0)
1800                                 return ret;
1801                         continue;
1802                 }
1803                 if (!strncmp(arg, "-y", 2)) {
1804                         ret = para_atoi32(arg + 2, &cto.lyrics_id);
1805                         if (ret < 0)
1806                                 return ret;
1807                         continue;
1808                 }
1809                 if (!strncmp(arg, "-i", 2)) {
1810                         ret = para_atoi32(arg + 2, &cto.image_id);
1811                         if (ret < 0)
1812                                 return ret;
1813                         continue;
1814                 }
1815                 if (!strcmp(arg, "-p")) {
1816                         cto.flags |= TOUCH_FLAG_FNM_PATHNAME;
1817                         continue;
1818                 }
1819                 if (!strcmp(arg, "-v")) {
1820                         cto.flags |= TOUCH_FLAG_VERBOSE;
1821                         continue;
1822                 }
1823                 break; /* non-option starting with dash */
1824         }
1825         if (i >= argc)
1826                 return -E_AFT_SYNTAX;
1827         ret = send_option_arg_callback_request(&query, argc - i,
1828                 argv + i, com_touch_callback, &result);
1829         if (ret > 0) {
1830                 send_buffer(fd, (char *)result.data);
1831                 free(result.data);
1832         } else
1833                 send_va_buffer(fd, "%s\n", PARA_STRERROR(-ret));
1834         return ret;
1835 }
1836
1837 enum rm_flags {
1838         RM_FLAG_VERBOSE = 1,
1839         RM_FLAG_FORCE = 2,
1840         RM_FLAG_FNM_PATHNAME = 4
1841 };
1842
1843 struct com_rm_data {
1844         uint32_t flags;
1845         struct para_buffer pb;
1846         unsigned num_removed;
1847 };
1848
1849 static int remove_audio_file(__a_unused struct osl_table *table,
1850                 struct osl_row *row, const char *name, void *data)
1851 {
1852         struct com_rm_data *crd = data;
1853         int ret;
1854
1855         if (crd->flags & RM_FLAG_VERBOSE)
1856                 para_printf(&crd->pb, "removing %s\n", name);
1857         ret = mood_delete_audio_file(row);
1858         if (ret < 0)
1859                 para_printf(&crd->pb, "%s: %s\n", name, PARA_STRERROR(-ret));
1860         ret = osl_del_row(audio_file_table, row);
1861         if (ret < 0)
1862                 para_printf(&crd->pb, "%s: %s\n", name, PARA_STRERROR(-ret));
1863         else
1864                 crd->num_removed++;
1865         return 1;
1866 }
1867
1868 static int com_rm_callback(const struct osl_object *query,
1869                 __a_unused struct osl_object *result)
1870 {
1871         struct com_rm_data crd = {.flags = *(uint32_t *)query->data};
1872         int ret;
1873         struct pattern_match_data pmd = {
1874                 .table = audio_file_table,
1875                 .loop_col_num = AFTCOL_HASH,
1876                 .match_col_num = AFTCOL_PATH,
1877                 .patterns = {.data = (char *)query->data + sizeof(uint32_t),
1878                         .size = query->size - sizeof(uint32_t)},
1879                 .data = &crd,
1880                 .action = remove_audio_file
1881         };
1882         if (crd.flags & RM_FLAG_FNM_PATHNAME)
1883                 pmd.fnmatch_flags |= FNM_PATHNAME;
1884         ret = for_each_matching_row(&pmd);
1885         if (ret < 0)
1886                 para_printf(&crd.pb, "%s\n", PARA_STRERROR(-ret));
1887         if (!crd.num_removed && !(crd.flags & RM_FLAG_FORCE))
1888                 para_printf(&crd.pb, "no matches -- nothing removed\n");
1889         else {
1890                 if (crd.flags & RM_FLAG_VERBOSE)
1891                         para_printf(&crd.pb, "removed %u files\n", crd.num_removed);
1892         }
1893         if (crd.pb.buf) {
1894                 result->data = crd.pb.buf;
1895                 result->size = crd.pb.size;
1896                 return 1;
1897         }
1898         return ret < 0? ret : 0;
1899 }
1900
1901 /* TODO options: -r (recursive) */
1902 int com_afs_rm(int fd, int argc,  char * const * const argv)
1903 {
1904         uint32_t flags = 0;
1905         struct osl_object query = {.data = &flags, .size = sizeof(flags)},
1906                 result;
1907         int i, ret;
1908
1909         for (i = 1; i < argc; i++) {
1910                 const char *arg = argv[i];
1911                 if (arg[0] != '-')
1912                         break;
1913                 if (!strcmp(arg, "--")) {
1914                         i++;
1915                         break;
1916                 }
1917                 if (!strcmp(arg, "-f")) {
1918                         flags |= RM_FLAG_FORCE;
1919                         continue;
1920                 }
1921                 if (!strcmp(arg, "-p")) {
1922                         flags |= RM_FLAG_FNM_PATHNAME;
1923                         continue;
1924                 }
1925                 if (!strcmp(arg, "-v")) {
1926                         flags |= RM_FLAG_VERBOSE;
1927                         continue;
1928                 }
1929                 break;
1930         }
1931         if (i >= argc)
1932                 return -E_AFT_SYNTAX;
1933         ret = send_option_arg_callback_request(&query, argc - i, argv + i,
1934                 com_rm_callback, &result);
1935         if (ret > 0) {
1936                 send_buffer(fd, (char *)result.data);
1937                 free(result.data);
1938         } else
1939                 send_va_buffer(fd, "%s\n", PARA_STRERROR(-ret));
1940         return ret;
1941 }
1942
1943 enum cpsi_flags {
1944         CPSI_FLAG_COPY_LYRICS_ID = 1,
1945         CPSI_FLAG_COPY_IMAGE_ID = 2,
1946         CPSI_FLAG_COPY_LASTPLAYED = 4,
1947         CPSI_FLAG_COPY_NUMPLAYED = 8,
1948         CPSI_FLAG_COPY_ATTRIBUTES = 16,
1949         CPSI_FLAG_VERBOSE = 32,
1950 };
1951
1952 struct cpsi_action_data {
1953         unsigned flags;
1954         unsigned num_copied;
1955         struct para_buffer pb;
1956         struct afs_info source_afsi;
1957 };
1958
1959 static int copy_selector_info(__a_unused struct osl_table *table,
1960                 struct osl_row *row, const char *name, void *data)
1961 {
1962         struct cpsi_action_data *cad = data;
1963         struct osl_object target_afsi_obj;
1964         int ret;
1965         struct afs_info target_afsi;
1966
1967         ret = get_afsi_object_of_row(row, &target_afsi_obj);
1968         if (ret < 0)
1969                 return ret;
1970         load_afsi(&target_afsi, &target_afsi_obj);
1971         if (cad->flags & CPSI_FLAG_COPY_LYRICS_ID)
1972                 target_afsi.lyrics_id = cad->source_afsi.lyrics_id;
1973         if (cad->flags & CPSI_FLAG_COPY_IMAGE_ID)
1974                 target_afsi.image_id = cad->source_afsi.image_id;
1975         if (cad->flags & CPSI_FLAG_COPY_LASTPLAYED)
1976                 target_afsi.last_played = cad->source_afsi.last_played;
1977         if (cad->flags & CPSI_FLAG_COPY_NUMPLAYED)
1978                 target_afsi.num_played = cad->source_afsi.num_played;
1979         if (cad->flags & CPSI_FLAG_COPY_ATTRIBUTES)
1980                 target_afsi.attributes = cad->source_afsi.attributes;
1981         save_afsi(&target_afsi, &target_afsi_obj); /* in-place update */
1982         cad->num_copied++;
1983         if (cad->flags & CPSI_FLAG_VERBOSE)
1984                 para_printf(&cad->pb, "copied afsi to %s\n", name);
1985         return 1;
1986 }
1987
1988 static int com_cpsi_callback(const struct osl_object *query,
1989                 struct osl_object *result)
1990 {
1991         struct cpsi_action_data cad = {.flags = *(unsigned *)query->data};
1992         int ret;
1993         char *source_path = (char *)query->data + sizeof(cad.flags);
1994
1995         ret = get_afsi_of_path(source_path, &cad.source_afsi);
1996         if (ret < 0)
1997                 goto out;
1998         struct pattern_match_data pmd = {
1999                 .table = audio_file_table,
2000                 .loop_col_num = AFTCOL_HASH,
2001                 .match_col_num = AFTCOL_PATH,
2002                 .patterns = {.data = source_path + strlen(source_path) + 1,
2003                         .size = query->size - sizeof(cad.flags)
2004                                 - strlen(source_path) - 1},
2005                 .data = &cad,
2006                 .action = copy_selector_info
2007         };
2008         ret = for_each_matching_row(&pmd);
2009 out:
2010         if (ret < 0)
2011                 para_printf(&cad.pb, "%s\n", PARA_STRERROR(-ret));
2012         if (cad.flags & CPSI_FLAG_VERBOSE) {
2013                 if (cad.num_copied)
2014                         para_printf(&cad.pb, "copied requested afsi from %s "
2015                                 "to %u files\n",
2016                                 source_path, cad.num_copied);
2017                 else
2018                         para_printf(&cad.pb, "nothing copied\n");
2019         }
2020         if (cad.pb.buf) {
2021                 result->data = cad.pb.buf;
2022                 result->size = cad.pb.size;
2023                 return 1;
2024         }
2025         return ret < 0? ret : 0;
2026 }
2027
2028 int com_cpsi(int fd, int argc,  char * const * const argv)
2029 {
2030         unsigned flags = 0;
2031         int i, ret;
2032         struct osl_object options = {.data = &flags, .size = sizeof(flags)},
2033                 result;
2034
2035         for (i = 1; i < argc; i++) {
2036                 const char *arg = argv[i];
2037                 if (arg[0] != '-')
2038                         break;
2039                 if (!strcmp(arg, "--")) {
2040                         i++;
2041                         break;
2042                 }
2043                 if (!strcmp(arg, "-y")) {
2044                         flags |= CPSI_FLAG_COPY_LYRICS_ID;
2045                         continue;
2046                 }
2047                 if (!strcmp(arg, "-i")) {
2048                         flags |= CPSI_FLAG_COPY_IMAGE_ID;
2049                         continue;
2050                 }
2051                 if (!strcmp(arg, "-l")) {
2052                         flags |= CPSI_FLAG_COPY_LASTPLAYED;
2053                         continue;
2054                 }
2055                 if (!strcmp(arg, "-n")) {
2056                         flags |= CPSI_FLAG_COPY_NUMPLAYED;
2057                         continue;
2058                 }
2059                 if (!strcmp(arg, "-a")) {
2060                         flags |= CPSI_FLAG_COPY_ATTRIBUTES;
2061                         continue;
2062                 }
2063                 if (!strcmp(arg, "-v")) {
2064                         flags |= CPSI_FLAG_VERBOSE;
2065                         continue;
2066                 }
2067                 break;
2068         }
2069         if (i + 1 >= argc) /* need at least souce file and pattern */
2070                 return -E_AFT_SYNTAX;
2071         if (!(flags & ~CPSI_FLAG_VERBOSE)) /* no copy flags given */
2072                 flags = ~(unsigned)CPSI_FLAG_VERBOSE | flags;
2073         ret = send_option_arg_callback_request(&options, argc - i, argv + i,
2074                 com_cpsi_callback, &result);
2075         if (ret > 0) {
2076                 send_buffer(fd, (char *)result.data);
2077                 free(result.data);
2078         } else
2079                 send_va_buffer(fd, "%s\n", PARA_STRERROR(-ret));
2080         return ret;
2081 }
2082
2083 /* TODO: optionally fix problems by removing offending rows */
2084 static int check_audio_file(struct osl_row *row, void *data)
2085 {
2086         char *path;
2087         struct para_buffer *pb = data;
2088         struct stat statbuf;
2089         int ret = get_audio_file_path_of_row(row, &path);
2090         struct afs_info afsi;
2091         char *blob_name;
2092
2093         if (ret < 0) {
2094                 para_printf(pb, "%s\n", PARA_STRERROR(-ret));
2095                 return 1;
2096         }
2097         if (stat(path, &statbuf) < 0)
2098                 para_printf(pb, "%s: stat error (%s)\n", path, strerror(errno));
2099         else {
2100                 if (!S_ISREG(statbuf.st_mode))
2101                         para_printf(pb, "%s: not a regular file\n", path);
2102         }
2103         ret = get_afsi_of_row(row, &afsi);
2104         if (ret < 0) {
2105                 para_printf(pb, "%s: %s\n", path, PARA_STRERROR(-ret));
2106                 return 1;
2107         }
2108         ret = lyr_get_name_by_id(afsi.lyrics_id, &blob_name);
2109         if (ret < 0)
2110                 para_printf(pb, "%s lyrics id %u: %s\n", path, afsi.lyrics_id,
2111                         PARA_STRERROR(-ret));
2112         ret = img_get_name_by_id(afsi.image_id, &blob_name);
2113         if (ret < 0)
2114                 para_printf(pb, "%s image id %u: %s\n", path, afsi.image_id,
2115                         PARA_STRERROR(-ret));
2116         return 1;
2117 }
2118
2119 int aft_check_callback(__a_unused const struct osl_object *query, struct osl_object *result)
2120 {
2121         struct para_buffer pb = {.buf = NULL};
2122
2123         para_printf(&pb, "checking audio file table...\n");
2124         audio_file_loop(&pb, check_audio_file);
2125         result->data = pb.buf;
2126         result->size = pb.size;
2127         return 1;
2128
2129 }
2130
2131
2132
2133 /**
2134  * Close the audio file table.
2135  *
2136  * \param flags Ususal flags that are passed to osl_close_table().
2137  *
2138  * \sa osl_close_table().
2139  */
2140 void aft_shutdown(enum osl_close_flags flags)
2141 {
2142         osl_close_table(audio_file_table, flags);
2143         audio_file_table = NULL;
2144 }
2145
2146 /**
2147  * Open the audio file table.
2148  *
2149  * \param ti Gets initialized by this function.
2150  * \param db The database directory.
2151  *
2152  * \return Positive on success, negative on errors.
2153  *
2154  * \sa osl_open_table().
2155  */
2156 int aft_init(struct table_info *ti, const char *db)
2157 {
2158         int ret;
2159
2160         audio_file_table_desc.dir = db;
2161         ti->desc = &audio_file_table_desc;
2162         ret = osl_open_table(ti->desc, &audio_file_table);
2163         if (ret >= 0) {
2164                 unsigned num;
2165                 osl_get_num_rows(audio_file_table, &num);
2166                 PARA_INFO_LOG("audio file table contains %d files\n", num);
2167                 return ret;
2168         }
2169         PARA_INFO_LOG("failed to open audio file table\n");
2170         audio_file_table = NULL;
2171         return ret == -E_NOENT? 1 : ret;
2172 }