Created
October 13, 2024 16:34
-
-
Save Dahie/c6431a0c601a7118a8f29a5171811c35 to your computer and use it in GitHub Desktop.
Immich-Delete-By-Search-Criteria.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # This is a script I wrote for automatic cleanup in immich. | |
| # Due to some faulty import, I had thousands of files I needed to clean and did not fast way except coding a small API-client. | |
| # | |
| # Change the URL, api-token and your search criteria | |
| # run: $ ruby clean-immich.rb | |
| require 'net/http' | |
| require 'json' | |
| class MetadataSearcher | |
| ## EDIT HERE | |
| API_KEY = "<api-token>" | |
| BASE_URL = "http://<immich-url>/api/search/metadata" | |
| CRITERIA = { originalFileName: "._IMG" } | |
| ## END editing | |
| def initialize | |
| @collector = [] | |
| end | |
| def delete_collected | |
| uri = URI(BASE_URL + '/api/assets') | |
| http = Net::HTTP.new(uri.host, uri.port) | |
| http.use_ssl = true | |
| request = Net::HTTP::Delete.new(uri.request_uri, | |
| 'Content-Type' => 'application/json', | |
| 'x-api-key' => API_KEY, | |
| 'Accept' => 'application/json') | |
| body = { | |
| "force" => true, | |
| "ids" => @collector.map { |h| h['id'] } | |
| }.to_json | |
| http.request(request, body) | |
| end | |
| def fetch_items(page) | |
| uri = URI(BASE_URL + '/api/search/metadata') | |
| http = Net::HTTP.new(uri.host, uri.port) | |
| http.use_ssl = true | |
| request = Net::HTTP::Post.new(uri.request_uri, | |
| 'Content-Type' => 'application/json', | |
| 'x-api-key' => API_KEY, | |
| 'Accept' => 'application/json') | |
| request.body = CRITERIA.merge({ page: page }).to_json | |
| response = http.request(request) | |
| response_body = JSON.parse(response.body) | |
| response_body['assets']['items'].each do |item| | |
| @collector << item | |
| end | |
| next_page = response_body['assets']['nextPage'] | |
| return if next_page.nil? | |
| page += 1 | |
| fetch_items(page) | |
| end | |
| def export_collector | |
| File.write('affected_files.json', @collector.to_json) | |
| end | |
| end | |
| searcher = MetadataSearcher.new | |
| searcher.fetch_items(1) # collect all items matching criteria | |
| searcher.export_collector # for debugging and as receipt | |
| searcher.delete_collected # request deletion from immich api |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment