Information Technology Grimoire

Version .0.0.1

IT Notes from various projects because I forget, and hopefully they help you too.

display app

This chrome app takes your supplied images and creates a screen saver.

File Structure

display_app
-icons/
	-icon_16.png
	-icon_48.png
	-icon_128.png
	-16x16-pixel-icons-20.png
-images/
	-2image1..xxx.gif
	-2image1..xxx.jpg
-background.js
-manifest.js
-window.js
-window.html

Installation

it installs like an app. Chrome > Manage Extensions > (developer mode) > Load unpacked > Select the display_app folder

Run it

It’s a chrome app, so, drag your bottom bar up to see all apps and look for it.

Pin it

Once it’s running, you can right click and pin to shelf.

Use it

  • escape key disables it
  • right arrow advances to next set
  • it will make a random gif or image on each screen
  • it will not duplicate on the same screens
  • runs indefinitely until you hit escape

window.html

<!DOCTYPE html>
<html>
  <body>
    <script src="window.js"></script>
  </body>
</html>

window.js

window.addEventListener('keydown', function(event) {
  if (event.key === "Escape") {
    let windows = chrome.app.window.getAll();
    for(let i = 0; i < windows.length; i++) {
      windows[i].close();
    }
  }
});

manifest.json

{
  "name": "Display Image on Multiple Screens",
  "version": "1.0",
  "manifest_version": 2,
  "app": {
    "background": {
      "scripts": ["background.js"]
    }
  },
  "permissions": ["system.display"],
  "icons": {
    "16": "icon_16.png",
    "128": "icon_128.png"
  }
}

background.js

const numJpgs = 344;
const numGifs = 317;

// creates a screen for each display, and puts random image in it for 60 seconds
// Right arrow refreshes new set sooner.   Esc closes the app.


// Other useful apps
// ShufflePaper - Randomize your wallpapers ghcndibmdbeipgggdddmecagpkllglpj
// Keep Awake - prevents screen lock bijihlabcfdnabacffofojgmehjdielb

let counter = 0;
let lastImages = [];

function getRandomImage() {
  let newImage;
  
  do {
    counter++;

    if (counter % 6 === 0) {  // Every 6th image will be a gif
      const randomIndex = Math.floor(Math.random() * numGifs + 1);
      newImage = 'images/2image' + randomIndex + '.gif';
    } else {
      const randomIndex = Math.floor(Math.random() * numJpgs + 1);
      newImage = 'images/2image' + randomIndex + '.jpg';
    }
  } while (lastImages.includes(newImage));  // Keep generating new images until we get one that hasn't been shown recently
  
  lastImages.push(newImage);
  if (lastImages.length > numDisplays) {
    lastImages.shift();  // Remove the oldest image from the list
  }
  
  return newImage;
}

chrome.app.runtime.onLaunched.addListener(function() {
  chrome.system.display.getInfo(function(displays) {
    let windows = [];
    numDisplays = displays.length;  // Get the number of displays

    // Create a window for each display
    for (let i = 0; i < numDisplays; i++) {
      let display = displays[i];
      let options = {
        'bounds': {
          'left': display.bounds.left,
          'top': display.bounds.top,
          'width': display.bounds.width,
          'height': display.bounds.height
        },
        'resizable': false,
        'frame': 'none'
      };

      chrome.app.window.create('window.html', options, function(createdWindow) {
        windows.push(createdWindow);
        createdWindow.contentWindow.onload = function() {
          let body = createdWindow.contentWindow.document.body;
          body.style.backgroundColor = 'black';
          body.style.display = 'flex';
          body.style.justifyContent = 'center';
          body.style.alignItems = 'center';
          body.style.margin = '0';
          body.style.height = '100vh';

          let imgElement = createdWindow.contentWindow.document.createElement('img');
          imgElement.style.display = 'block';
          imgElement.style.maxHeight = '100%';
          imgElement.style.maxWidth = '100%';
          imgElement.style.border = 'none';
          imgElement.src = getRandomImage();
          body.appendChild(imgElement);

          body.addEventListener('keydown', function(e) {
            if (e.keyCode === 39) {  // 39 is the keyCode for the right arrow key
              for (let win of windows) {
                let imgElement = win.contentWindow.document.querySelector('img');
                imgElement.src = getRandomImage();
              }
            }
          });
        };
      });
    }

    // Set an interval to change the image every 60 seconds
    setInterval(function() {
      for (let win of windows) {
        let imgElement = win.contentWindow.document.querySelector('img');
        imgElement.src = getRandomImage();
      }
    }, 60000);  // 60000 milliseconds = 60 seconds
  });
});

Duplicate File Deletion

import os
import glob
import hashlib
import sys

def calculate_md5(filename):
    hash_md5 = hashlib.md5()
    with open(filename, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()

def find_duplicates(folder_path, file_types, delete=False):
    file_dict = {}
    size_dict = {}

    for file_type in file_types:
        files = glob.glob(os.path.join(folder_path, f'*.{file_type}'))
        for file in files:
            file_size = os.path.getsize(file)
            if file_size not in size_dict:
                size_dict[file_size] = [file]
            else:
                size_dict[file_size].append(file)
    
    for files in size_dict.values():
        if len(files) > 1:
            for file in files:
                file_md5 = calculate_md5(file)
                if file_md5 not in file_dict:
                    file_dict[file_md5] = [file]
                else:
                    file_dict[file_md5].append(file)
    
    for key, value in file_dict.items():
        if len(value) > 1:
            keep_file = value[0]
            del_files = value[1:]
            for filename in del_files:
                if delete:
                    print(f"Deleting {filename} (MD5: {key}), keeping {keep_file}")
                    os.remove(filename)
                else:
                    print(f"[DRY RUN] Would delete {filename} (MD5: {key}), keeping {keep_file}")

if __name__ == "__main__":
    folder_path = os.getcwd()  # Get the current directory
    file_types = ['gif', 'jpg', 'jpeg', 'png', 'bmp']  # Added additional image formats

    # Check if '--delete' flag is provided
    if '--delete' in sys.argv:
        delete_files = True
    else:
        delete_files = False
        print("This is a dry run. To actually delete the files, add the --delete flag.")

    find_duplicates(folder_path, file_types, delete_files)

File Renamer

# Import necessary modules
import os
import glob

# Define a function to rename files based on the given file types in the provided folder
def rename_files(folder_path, file_types):
    # Iterate through each file type
    for file_type in file_types:
        # Get a list of files of the current file type in the folder
        files = glob.glob(os.path.join(folder_path, f'*.{file_type}'))
        
        index = 1  # Start the index at 1 for naming
        # Iterate through each file in the list
        for file in files:
            # Generate the new name based on the index
            new_name = os.path.join(folder_path, f'2image{index}.{file_type}')
            
            # If a file with the new name already exists, increment the index to find an unused name
            while os.path.exists(new_name):
                index += 1
                new_name = os.path.join(folder_path, f'2image{index}.{file_type}')
            
            # Rename the file to the new name
            os.rename(file, new_name)
            index += 1  # Increment the index for the next file

# Main execution starts here
if __name__ == "__main__":
    # Get the directory where the script resides
    folder_path = os.path.dirname(os.path.realpath(__file__))
    # Define the file types to look for
    file_types = ['gif', 'jpg', 'jpeg', 'png', 'bmp']  # Added additional image formats for completeness
    # Call the function to rename files in the directory
    rename_files(folder_path, file_types)