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