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