CCMain.m 247 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644
  1. //
  2. // CCMain.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCPhotosCameraUpload.h"
  26. #import "CCSynchronize.h"
  27. #import "CCTransfersCell.h"
  28. #import "OCActivity.h"
  29. #import "OCNotifications.h"
  30. #import "OCNotificationsAction.h"
  31. #import "OCFrameworkConstants.h"
  32. #import "OCCapabilities.h"
  33. #import "CTAssetCheckmark.h"
  34. #import "NCBridgeSwift.h"
  35. #define alertCreateFolder 1
  36. #define alertCreateFolderCrypto 2
  37. #define alertRename 3
  38. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate, CCActionsDownloadThumbnailDelegate, CCActionsSettingFavoriteDelegate>
  39. {
  40. tableMetadata *_metadata;
  41. BOOL _isRoot;
  42. BOOL _isViewDidLoad;
  43. BOOL _isOfflineServerUrl;
  44. BOOL _isPickerCriptate; // if is cryptated image or video back from picker
  45. BOOL _isSelectedMode;
  46. NSMutableArray *_selectedMetadatas;
  47. NSMutableArray *_queueSelector;
  48. NSUInteger _numSelectedMetadatas;
  49. UIImageView *_ImageTitleHomeCryptoCloud;
  50. UIView *_reMenuBackgroundView;
  51. UITapGestureRecognizer *_singleFingerTap;
  52. NSString *_directoryGroupBy;
  53. NSString *_directoryOrder;
  54. NSUInteger _failedAttempts;
  55. NSDate *_lockUntilDate;
  56. NSString *_fatherPermission;
  57. UIRefreshControl *_refreshControl;
  58. UIDocumentInteractionController *_docController;
  59. CCHud *_hud;
  60. CCHud *_hudDeterminate;
  61. // Datasource
  62. CCSectionDataSourceMetadata *_sectionDataSource;
  63. NSDate *_dateReadDataSource;
  64. // Search
  65. BOOL _isSearchMode;
  66. NSString *_searchFileName;
  67. NSMutableArray *_searchResultMetadatas;
  68. NSString *_depth;
  69. NSString *_noFilesSearchTitle;
  70. NSString *_noFilesSearchDescription;
  71. // Login
  72. CCLoginWeb *_loginWeb;
  73. CCLogin *_loginVC;
  74. }
  75. @end
  76. @implementation CCMain
  77. #pragma --------------------------------------------------------------------------------------------
  78. #pragma mark ===== Init =====
  79. #pragma --------------------------------------------------------------------------------------------
  80. - (id)initWithCoder:(NSCoder *)aDecoder
  81. {
  82. if (self = [super initWithCoder:aDecoder]) {
  83. _directoryOrder = [CCUtility getOrderSettings];
  84. _directoryGroupBy = [CCUtility getGroupBySettings];
  85. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  86. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  87. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  88. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  89. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  90. }
  91. return self;
  92. }
  93. #pragma --------------------------------------------------------------------------------------------
  94. #pragma mark ===== View =====
  95. #pragma --------------------------------------------------------------------------------------------
  96. - (void)viewDidLoad
  97. {
  98. [super viewDidLoad];
  99. // init object
  100. _metadata = [tableMetadata new];
  101. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  102. _hudDeterminate = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  103. _selectedMetadatas = [NSMutableArray new];
  104. _queueSelector = [NSMutableArray new];
  105. _sectionDataSource = [CCSectionDataSourceMetadata new];
  106. _isViewDidLoad = YES;
  107. _fatherPermission = @"";
  108. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  109. _searchResultMetadatas = [NSMutableArray new];
  110. _searchFileName = @"";
  111. _depth = @"0";
  112. _noFilesSearchTitle = @"";
  113. _noFilesSearchDescription = @"";
  114. // delegate
  115. self.tableView.delegate = self;
  116. self.tableView.tableFooterView = [UIView new];
  117. self.tableView.separatorColor = [NCBrandColor sharedInstance].seperator;
  118. self.tableView.emptyDataSetDelegate = self;
  119. self.tableView.emptyDataSetSource = self;
  120. self.searchController.delegate = self;
  121. self.searchController.searchBar.delegate = self;
  122. [[CCNetworking sharedNetworking] settingDelegate:self];
  123. // Custom Cell
  124. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  125. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  126. // long press recognizer TableView
  127. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  128. [self.tableView addGestureRecognizer:longPressRecognizer];
  129. // Pull-to-Refresh
  130. [self createRefreshControl];
  131. // Register for 3D Touch Previewing if available
  132. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  133. {
  134. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  135. }
  136. // Back Button
  137. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]])
  138. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"] style:UIBarButtonItemStylePlain target:nil action:nil];
  139. // reMenu Background
  140. _reMenuBackgroundView = [[UIView alloc] init];
  141. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  142. // if this is not Main (the Main uses inizializeMain)
  143. if (_isRoot == NO && app.activeAccount.length > 0) {
  144. // Settings this folder & delegate & Loading datasource
  145. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  146. // Load Datasource
  147. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  148. // Read Folder
  149. [self readFolderWithForced:NO serverUrl:_serverUrl];
  150. }
  151. // Title
  152. [self setTitle];
  153. // Search
  154. self.definesPresentationContext = YES;
  155. self.searchController.searchResultsUpdater = self;
  156. self.searchController.dimsBackgroundDuringPresentation = NO;
  157. self.tableView.tableHeaderView = self.searchController.searchBar;
  158. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].seperator;
  159. [self.searchController.searchBar sizeToFit];
  160. self.searchController.searchBar.delegate = self;
  161. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_this_folder_",nil);
  162. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12) {
  163. if (_isRoot)
  164. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),NSLocalizedString(@"_search_all_folders_",nil), nil];
  165. else
  166. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),NSLocalizedString(@"_search_sub_folder_",nil), nil];
  167. } else {
  168. self.searchController.searchBar.scopeButtonTitles = nil;
  169. }
  170. // Hide Search Filed on Load
  171. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  172. }
  173. // Apparirà
  174. - (void)viewWillAppear:(BOOL)animated
  175. {
  176. [super viewWillAppear:animated];
  177. // test
  178. if (app.activeAccount.length == 0)
  179. return;
  180. // Settings this folder & delegate & Loading datasource
  181. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  182. [[CCNetworking sharedNetworking] settingDelegate:self];
  183. // Color
  184. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  185. [app aspectTabBar:self.tabBarController.tabBar hidden:NO];
  186. if (_isSelectedMode)
  187. [self setUINavigationBarSelected];
  188. else
  189. [self setUINavigationBarDefault];
  190. // Plus Button
  191. [app plusButtonVisibile:true];
  192. }
  193. // E' arrivato
  194. - (void)viewDidAppear:(BOOL)animated
  195. {
  196. [super viewDidAppear:animated];
  197. // Active Main
  198. app.activeMain = self;
  199. // Test viewDidLoad
  200. if (_isViewDidLoad) {
  201. _isViewDidLoad = NO;
  202. } else {
  203. if (app.activeAccount.length > 0) {
  204. // Load Datasource
  205. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  206. // Read Folder
  207. [self readFolderWithForced:NO serverUrl:_serverUrl];
  208. }
  209. }
  210. // Title
  211. [self setTitle];
  212. }
  213. - (void)viewWillDisappear:(BOOL)animated
  214. {
  215. [super viewWillDisappear:animated];
  216. [self closeAllMenu];
  217. }
  218. - (void)didReceiveMemoryWarning
  219. {
  220. [super didReceiveMemoryWarning];
  221. // Dispose of any resources that can be recreated.
  222. }
  223. - (BOOL)prefersStatusBarHidden
  224. {
  225. return NO;
  226. }
  227. // detect scroll for remove keyboard in search mode
  228. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  229. {
  230. if (_isSearchMode && scrollView == self.tableView) {
  231. [self.searchController.searchBar endEditing:YES];
  232. }
  233. }
  234. - (void)changeTheming
  235. {
  236. if (self.isViewLoaded && self.view.window)
  237. [app changeTheming:self];
  238. // Refresh control
  239. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  240. // Reload Table View
  241. [self.tableView reloadData];
  242. }
  243. #pragma --------------------------------------------------------------------------------------------
  244. #pragma mark ===== Initizlize Mail =====
  245. #pragma --------------------------------------------------------------------------------------------
  246. - (void)initializeMain:(NSNotification *)notification
  247. {
  248. _directoryGroupBy = nil;
  249. _directoryOrder = nil;
  250. _dateReadDataSource = nil;
  251. // test
  252. if (app.activeAccount.length == 0)
  253. return;
  254. if ([app.listMainVC count] == 0 || _isRoot) {
  255. // This is Root
  256. _isRoot = YES;
  257. // Crypto Mode
  258. if ([[CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]] length] == 0) {
  259. app.isCryptoCloudMode = NO;
  260. } else {
  261. app.isCryptoCloudMode = YES;
  262. }
  263. // go Home
  264. [self.navigationController popToRootViewControllerAnimated:NO];
  265. // Remove search mode
  266. [self cancelSearchBar];
  267. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  268. _isFolderEncrypted = NO;
  269. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  270. // add list
  271. [app.listMainVC setObject:self forKey:_serverUrl];
  272. // setting Networking
  273. [[CCNetworking sharedNetworking] settingDelegate:self];
  274. [[CCNetworking sharedNetworking] settingAccount];
  275. // populate shared Link & User variable
  276. NSArray *results = [[NCManageDatabase sharedInstance] getShares];
  277. if (results) {
  278. app.sharesLink = results[0];
  279. app.sharesUserAndGroup = results[1];
  280. }
  281. // Setting Theming
  282. [app settingThemingColorBrand];
  283. // Load Datasource
  284. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  285. // Load Folder
  286. [self readFolderWithForced:NO serverUrl:_serverUrl];
  287. // Load photo datasorce
  288. if (app.activePhotosCameraUpload)
  289. [app.activePhotosCameraUpload reloadDatasourceForced];
  290. // remove all of detail
  291. if (app.activeDetail)
  292. [app.activeDetail removeAllView];
  293. // remove all Notification Messages
  294. [app.listOfNotifications removeAllObjects];
  295. // home main
  296. app.homeMain = self;
  297. // Initializations
  298. [app applicationInitialized];
  299. } else {
  300. // reload datasource
  301. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  302. }
  303. }
  304. #pragma --------------------------------------------------------------------------------------------
  305. #pragma mark ==== DZNEmptyDataSetSource ====
  306. #pragma --------------------------------------------------------------------------------------------
  307. /*
  308. - (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView
  309. {
  310. if(_isSearchMode)
  311. return NO;
  312. else
  313. return YES;
  314. }
  315. */
  316. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  317. {
  318. return YES;
  319. }
  320. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  321. {
  322. return [UIColor whiteColor];
  323. }
  324. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  325. {
  326. if (_isSearchMode)
  327. return [UIImage imageNamed:@"searchBig"];
  328. else
  329. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"filesNoFiles"] color:[NCBrandColor sharedInstance].brand];
  330. }
  331. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  332. {
  333. NSString *text;
  334. if (_isSearchMode)
  335. text = _noFilesSearchTitle;
  336. else
  337. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  338. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  339. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  340. }
  341. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  342. {
  343. NSString *text;
  344. if (_isSearchMode)
  345. text = _noFilesSearchDescription;
  346. else
  347. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  348. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  349. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  350. paragraph.alignment = NSTextAlignmentCenter;
  351. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  352. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  353. }
  354. #pragma --------------------------------------------------------------------------------------------
  355. #pragma mark ===== AlertView =====
  356. #pragma --------------------------------------------------------------------------------------------
  357. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  358. {
  359. [alertView dismissWithClickedButtonIndex:buttonIndex animated:YES];
  360. if (alertView.tag == alertCreateFolder && buttonIndex == 1) [self createFolder:[alertView textFieldAtIndex:0].text folderCameraUpload:NO];
  361. if (alertView.tag == alertCreateFolderCrypto && buttonIndex == 1) [self createFolderEncrypted:[alertView textFieldAtIndex:0].text];
  362. if (alertView.tag == alertRename && buttonIndex == 1) {
  363. if ([_metadata.model isEqualToString:@"note"]) {
  364. [self renameNote:_metadata fileName:[alertView textFieldAtIndex:0].text];
  365. } else {
  366. [self renameFile:_metadata fileName:[alertView textFieldAtIndex:0].text];
  367. }
  368. }
  369. }
  370. // accept only number char > 0
  371. - (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
  372. {
  373. /* Retrieve a text field at an index -
  374. raises NSRangeException when textFieldIndex is out-of-bounds.
  375. The field at index 0 will be the first text field
  376. (the single field or the login field),
  377. The field at index 1 will be the password field. */
  378. /*
  379. 1> Get the Text Field in alertview
  380. 2> Get the text of that Text Field
  381. 3> Verify that text length
  382. 4> return YES or NO Based on the length
  383. */
  384. return ([[[alertView textFieldAtIndex:0] text] length]>0)?YES:NO;
  385. }
  386. #pragma --------------------------------------------------------------------------------------------
  387. #pragma mark ===== Graphic Window =====
  388. #pragma --------------------------------------------------------------------------------------------
  389. - (void)createRefreshControl
  390. {
  391. _refreshControl = [UIRefreshControl new];
  392. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  393. _refreshControl.backgroundColor = [UIColor colorWithRed:235.0/255.0 green:235.0/255.0 blue:235.0/255.0 alpha:1.0];
  394. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  395. [self setRefreshControl:_refreshControl];
  396. }
  397. - (void)deleteRefreshControl
  398. {
  399. [_refreshControl endRefreshing];
  400. self.refreshControl = nil;
  401. }
  402. - (void)refreshControlTarget
  403. {
  404. [self readFolderWithForced:YES serverUrl:_serverUrl];
  405. // Actuate `Peek` feedback (weak boom)
  406. AudioServicesPlaySystemSound(1519);
  407. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  408. }
  409. - (void)setTitle
  410. {
  411. // Color text self.navigationItem.title
  412. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  413. if (_isSelectedMode) {
  414. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  415. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  416. self.navigationItem.titleView = nil;
  417. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  418. } else {
  419. // we are in home : LOGO BRAND
  420. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  421. self.navigationItem.title = nil;
  422. if ([app.reachability isReachable] == NO)
  423. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogoOffline"]];
  424. else
  425. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"]];
  426. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  427. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuLogo)];
  428. [singleTap setNumberOfTapsRequired:1];
  429. [_ImageTitleHomeCryptoCloud addGestureRecognizer:singleTap];
  430. self.navigationItem.titleView = _ImageTitleHomeCryptoCloud;
  431. } else {
  432. self.navigationItem.title = _titleMain;
  433. }
  434. }
  435. }
  436. - (void)setUINavigationBarDefault
  437. {
  438. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  439. UIBarButtonItem *buttonMore, *buttonNotification;
  440. // =
  441. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationControllerMenu"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  442. buttonMore.enabled = true;
  443. // <
  444. self.navigationController.navigationBar.hidden = NO;
  445. // Notification
  446. if ([app.listOfNotifications count] > 0) {
  447. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"notification"] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  448. buttonNotification.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  449. buttonNotification.enabled = true;
  450. }
  451. if (buttonNotification)
  452. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  453. else
  454. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  455. self.navigationItem.leftBarButtonItem = nil;
  456. }
  457. - (void)setUINavigationBarSelected
  458. {
  459. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  460. UIImage *icon = [UIImage imageNamed:@"navigationControllerMenu"];
  461. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  462. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  463. self.navigationItem.leftBarButtonItem = leftButton;
  464. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  465. }
  466. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  467. {
  468. [self closeAllMenu];
  469. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  470. }];
  471. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  472. }
  473. - (void)cancelSelect
  474. {
  475. [self tableViewSelect:NO];
  476. [app.reSelectMenu close];
  477. }
  478. - (void)closeAllMenu
  479. {
  480. // close Menu
  481. [app.reSelectMenu close];
  482. [app.reMainMenu close];
  483. // Close Menu Logo
  484. [CCMenuAccount dismissMenu];
  485. }
  486. #pragma --------------------------------------------------------------------------------------------
  487. #pragma mark ===== Document Picker =====
  488. #pragma --------------------------------------------------------------------------------------------
  489. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  490. {
  491. NSLog(@"Cancelled");
  492. }
  493. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  494. {
  495. NSLog(@"Cancelled");
  496. }
  497. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  498. {
  499. documentPicker.delegate = self;
  500. [self presentViewController:documentPicker animated:YES completion:nil];
  501. }
  502. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  503. {
  504. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  505. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  506. __block NSError *error;
  507. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  508. NSString *fileName = [url lastPathComponent];
  509. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileName];
  510. NSData *data = [NSData dataWithContentsOfURL:newURL];
  511. if (data && error == nil) {
  512. if ([data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error]) {
  513. // Upload File
  514. [[CCNetworking sharedNetworking] uploadFile:fileName serverUrl:_serverUrl cryptated:_isPickerCriptate onlyPlist:NO session:k_upload_session taskStatus: k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  515. } else {
  516. [app messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  517. }
  518. } else {
  519. [app messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  520. }
  521. }];
  522. }
  523. }
  524. - (void)openImportDocumentPicker
  525. {
  526. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  527. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  528. documentProviderMenu.popoverPresentationController.sourceView = self.view;
  529. documentProviderMenu.popoverPresentationController.sourceRect = self.view.bounds;
  530. documentProviderMenu.delegate = self;
  531. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  532. }
  533. #pragma --------------------------------------------------------------------------------------------
  534. #pragma mark ===== Assets Picker =====
  535. #pragma --------------------------------------------------------------------------------------------
  536. - (void)openAssetsPickerController
  537. {
  538. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  539. checkmark.tintColor = [NCBrandColor sharedInstance].brand;
  540. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeTop];
  541. UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedIn:[CTAssetsPickerController class], nil];
  542. [app aspectNavigationControllerBar:navBar encrypted:NO online:YES hidden:NO];
  543. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
  544. dispatch_async(dispatch_get_main_queue(), ^{
  545. // init picker
  546. CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
  547. // set delegate
  548. picker.delegate = self;
  549. // to show selection order
  550. //picker.showsSelectionIndex = YES;
  551. // to present picker as a form sheet in iPad
  552. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  553. picker.modalPresentationStyle = UIModalPresentationFormSheet;
  554. // present picker
  555. [self presentViewController:picker animated:YES completion:nil];
  556. });
  557. }];
  558. }
  559. - (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSMutableArray *)assets
  560. {
  561. [picker dismissViewControllerAnimated:YES completion:^{
  562. CreateFormUploadAssets *form = [[CreateFormUploadAssets alloc] init:_titleMain serverUrl:_serverUrl assets:assets cryptated:_isPickerCriptate session:k_upload_session];
  563. form.title = NSLocalizedString(@"_upload_photos_videos_", nil);
  564. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  565. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  566. //navController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
  567. [self presentViewController:navigationController animated:YES completion:nil];
  568. }];
  569. }
  570. #pragma --------------------------------------------------------------------------------------------
  571. #pragma mark ===== UIDocumentInteractionControllerDelegate =====
  572. #pragma --------------------------------------------------------------------------------------------
  573. - (void)documentInteractionControllerDidDismissOptionsMenu:(UIDocumentInteractionController *)controller
  574. {
  575. // evitiamo il rimando della eventuale photo e/o video
  576. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  577. if (tableAccount.cameraUpload) {
  578. [[NCManageDatabase sharedInstance] setAccountCameraUploadDateAssetType:PHAssetMediaTypeImage assetDate:[NSDate date]];
  579. [[NCManageDatabase sharedInstance] setAccountCameraUploadDateAssetType:PHAssetMediaTypeVideo assetDate:[NSDate date]];
  580. }
  581. }
  582. #pragma --------------------------------------------------------------------------------------------
  583. #pragma mark ===== UnZipFile =====
  584. #pragma --------------------------------------------------------------------------------------------
  585. - (void)unZipFile:(NSString *)fileID
  586. {
  587. [_hudDeterminate visibleHudTitle:NSLocalizedString(@"_unzip_in_progress_", nil) mode:MBProgressHUDModeDeterminate color:nil];
  588. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  589. NSString *fileZip = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID];
  590. [SSZipArchive unzipFileAtPath:fileZip toDestination:[CCUtility getDirectoryLocal] overwrite:YES password:nil progressHandler:^(NSString *entry, unz_file_info zipInfo, long entryNumber, long total) {
  591. dispatch_async(dispatch_get_main_queue(), ^{
  592. float progress = (float) entryNumber / (float)total;
  593. [_hudDeterminate progress:progress];
  594. });
  595. } completionHandler:^(NSString *path, BOOL succeeded, NSError *error) {
  596. dispatch_async(dispatch_get_main_queue(), ^{
  597. [_hudDeterminate hideHud];
  598. if (succeeded) [app messageNotification:@"_info_" description:@"_file_unpacked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  599. else [app messageNotification:@"_error_" description:[NSString stringWithFormat:@"Error %ld", (long)error.code] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  600. });
  601. }];
  602. });
  603. }
  604. #pragma --------------------------------------------------------------------------------------------
  605. #pragma mark ===== Create New (OpenModel) =====
  606. #pragma --------------------------------------------------------------------------------------------
  607. - (void)openModel:(NSString *)tipo isNew:(BOOL)isnew
  608. {
  609. UIViewController *viewController;
  610. NSString *fileName, *uuid, *fileID, *serverUrl;
  611. NSIndexPath * index = [self.tableView indexPathForSelectedRow];
  612. [self.tableView deselectRowAtIndexPath:index animated:NO];
  613. if (isnew) {
  614. fileName = nil;
  615. uuid = [CCUtility getUUID];
  616. fileID = nil;
  617. serverUrl = _serverUrl;
  618. } else {
  619. fileName = _metadata.fileName;
  620. uuid = _metadata.uuid;
  621. fileID = _metadata.fileID;
  622. serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  623. }
  624. if ([tipo isEqualToString:@"cartadicredito"])
  625. viewController = [[CCCartaDiCredito alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  626. if ([tipo isEqualToString:@"bancomat"])
  627. viewController = [[CCBancomat alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  628. if ([tipo isEqualToString:@"contocorrente"])
  629. viewController = [[CCContoCorrente alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  630. if ([tipo isEqualToString:@"accountweb"])
  631. viewController = [[CCAccountWeb alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  632. if ([tipo isEqualToString:@"patenteguida"])
  633. viewController = [[CCPatenteGuida alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  634. if ([tipo isEqualToString:@"cartaidentita"])
  635. viewController = [[CCCartaIdentita alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  636. if ([tipo isEqualToString:@"passaporto"])
  637. viewController = [[CCPassaporto alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  638. if ([tipo isEqualToString:@"note"]) {
  639. viewController = [[CCNote alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  640. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  641. [self presentViewController:navigationController animated:YES completion:nil];
  642. } else {
  643. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  644. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  645. [self presentViewController:navigationController animated:YES completion:nil];
  646. }
  647. }
  648. // New folder or new photo or video
  649. - (void)returnCreate:(NSInteger)type
  650. {
  651. switch (type) {
  652. /* PLAIN */
  653. case k_returnCreateFolderPlain: {
  654. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  655. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  656. alertView.tag = alertCreateFolder;
  657. [alertView show];
  658. }
  659. break;
  660. case k_returnCreateFotoVideoPlain: {
  661. _isPickerCriptate = false;
  662. [self openAssetsPickerController];
  663. }
  664. break;
  665. case k_returnCreateFilePlain: {
  666. _isPickerCriptate = false;
  667. [self openImportDocumentPicker];
  668. }
  669. break;
  670. /* ENCRYPTED */
  671. case k_returnCreateFolderEncrypted: {
  672. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  673. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  674. alertView.tag = alertCreateFolderCrypto;
  675. [alertView show];
  676. }
  677. break;
  678. case k_returnCreateFotoVideoEncrypted: {
  679. _isPickerCriptate = true;
  680. [self openAssetsPickerController];
  681. }
  682. break;
  683. case k_returnCreateFileEncrypted: {
  684. _isPickerCriptate = true;
  685. [self openImportDocumentPicker];
  686. }
  687. break;
  688. /* UTILITY */
  689. case k_returnNote:
  690. [self openModel:@"note" isNew:true];
  691. break;
  692. case k_returnAccountWeb:
  693. [self openModel:@"accountweb" isNew:true];
  694. break;
  695. /* BANK */
  696. case k_returnCartaDiCredito:
  697. [self openModel:@"cartadicredito" isNew:true];
  698. break;
  699. case k_returnBancomat:
  700. [self openModel:@"bancomat" isNew:true];
  701. break;
  702. case k_returnContoCorrente:
  703. [self openModel:@"contocorrente" isNew:true];
  704. break;
  705. /* DOCUMENT */
  706. case k_returnPatenteGuida:
  707. [self openModel:@"patenteguida" isNew:true];
  708. break;
  709. case k_returnCartaIdentita:
  710. [self openModel:@"cartaidentita" isNew:true];
  711. break;
  712. case k_returnPassaporto:
  713. [self openModel:@"passaporto" isNew:true];
  714. break;
  715. }
  716. }
  717. #pragma --------------------------------------------------------------------------------------------
  718. #pragma mark ===== Save selected File =====
  719. #pragma --------------------------------------------------------------------------------------------
  720. -(void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  721. {
  722. if (error)
  723. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  724. else
  725. [app messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:error.code];
  726. }
  727. - (void)saveSelectedFiles
  728. {
  729. NSLog(@"[LOG] Start download selected files ...");
  730. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  731. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  732. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  733. for (tableMetadata *metadata in metadatas) {
  734. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file] && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  735. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  736. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorSave selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  737. }
  738. }
  739. [_hud hideHud];
  740. });
  741. [self tableViewSelect:NO];
  742. }
  743. #pragma --------------------------------------------------------------------------------------------
  744. #pragma mark ===== Change Password =====
  745. #pragma --------------------------------------------------------------------------------------------
  746. - (void) loginSuccess:(NSInteger)loginType
  747. {
  748. [self readFolderWithForced:YES serverUrl:_serverUrl];
  749. }
  750. - (void)changePasswordAccount
  751. {
  752. // Brand
  753. if ([NCBrandOptions sharedInstance].use_login_web) {
  754. _loginWeb = [CCLoginWeb new];
  755. _loginWeb.delegate = self;
  756. _loginWeb.loginType = loginModifyPasswordUser;
  757. dispatch_async(dispatch_get_main_queue(), ^ {
  758. [_loginWeb presentModalWithDefaultTheme:self];
  759. });
  760. } else {
  761. _loginVC = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  762. _loginVC.delegate = self;
  763. _loginVC.loginType = loginModifyPasswordUser;
  764. [self presentViewController:_loginVC animated:YES completion:nil];
  765. }
  766. }
  767. #pragma mark -
  768. #pragma --------------------------------------------------------------------------------------------
  769. #pragma mark ===== Peek & Pop =====
  770. #pragma --------------------------------------------------------------------------------------------
  771. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  772. {
  773. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  774. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  775. if (metadata.thumbnailExists && !metadata.cryptated) {
  776. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  777. if (cell) {
  778. previewingContext.sourceRect = cell.frame;
  779. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  780. vc.delegate = self;
  781. vc.metadata = metadata;
  782. return vc;
  783. }
  784. }
  785. return nil;
  786. }
  787. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  788. {
  789. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  790. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  791. }
  792. #pragma mark -
  793. #pragma --------------------------------------------------------------------------------------------
  794. #pragma mark ==== External Sites ====
  795. #pragma --------------------------------------------------------------------------------------------
  796. - (void)getExternalSitesServerSuccess:(NSArray *)listOfExternalSites
  797. {
  798. [[NCManageDatabase sharedInstance] deleteExternalSites];
  799. for (OCExternalSites *tableExternalSites in listOfExternalSites)
  800. [[NCManageDatabase sharedInstance] addExternalSites:tableExternalSites];
  801. }
  802. - (void)getExternalSitesServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  803. {
  804. NSLog(@"[LOG] No External Sites found");
  805. }
  806. #pragma --------------------------------------------------------------------------------------------
  807. #pragma mark ==== Activity ====
  808. #pragma --------------------------------------------------------------------------------------------
  809. - (void)getActivityServerSuccess:(NSArray *)listOfActivity
  810. {
  811. [[NCManageDatabase sharedInstance] addActivityServer:listOfActivity];
  812. // Reload Activity Data Source
  813. [app.activeActivity reloadDatasource];
  814. }
  815. - (void)getActivityServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  816. {
  817. NSLog(@"[LOG] No Activity found");
  818. }
  819. #pragma --------------------------------------------------------------------------------------------
  820. #pragma mark ==== Notification ====
  821. #pragma --------------------------------------------------------------------------------------------
  822. - (void)getNotificationServerSuccess:(NSArray *)listOfNotifications
  823. {
  824. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  825. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  826. // Order by date
  827. NSArray *sortedListOfNotifications = [listOfNotifications sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  828. OCNotifications *notification1 = obj1, *notification2 = obj2;
  829. return [notification2.date compare: notification1.date];
  830. }];
  831. // verify if listOfNotifications is changed
  832. NSString *old = @"", *new = @"";
  833. for (OCNotifications *notification in listOfNotifications)
  834. new = [new stringByAppendingString:@(notification.idNotification).stringValue];
  835. for (OCNotifications *notification in appDelegate.listOfNotifications)
  836. old = [old stringByAppendingString:@(notification.idNotification).stringValue];
  837. if (![new isEqualToString:old]) {
  838. appDelegate.listOfNotifications = [[NSMutableArray alloc] initWithArray:sortedListOfNotifications];
  839. // reload Notification view
  840. dispatch_async(dispatch_get_main_queue(), ^{
  841. [[NSNotificationCenter defaultCenter] postNotificationName:@"notificationReloadData" object:nil];
  842. });
  843. }
  844. // Update NavigationBar
  845. if (!_isSelectedMode) {
  846. [self performSelectorOnMainThread:@selector(setUINavigationBarDefault) withObject:nil waitUntilDone:NO];
  847. }
  848. });
  849. }
  850. - (void)getNotificationServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  851. {
  852. // Update NavigationBar
  853. if (!_isSelectedMode)
  854. [self setUINavigationBarDefault];
  855. }
  856. - (void)viewNotification
  857. {
  858. if ([app.listOfNotifications count] > 0) {
  859. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  860. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  861. [self presentViewController:notificationVC animated:YES completion:nil];
  862. }
  863. }
  864. #pragma --------------------------------------------------------------------------------------------
  865. #pragma mark ==== User Profile ====
  866. #pragma --------------------------------------------------------------------------------------------
  867. - (void)getUserProfileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  868. {
  869. if (errorCode == 401)
  870. [self changePasswordAccount];
  871. }
  872. - (void)getUserProfileSuccess:(CCMetadataNet *)metadataNet userProfile:(OCUserProfile *)userProfile
  873. {
  874. [[NCManageDatabase sharedInstance] setAccountsUserProfile:userProfile];
  875. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  876. NSString *address = [NSString stringWithFormat:@"%@/index.php/avatar/%@/128", app.activeUrl, app.activeUser];
  877. UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  878. if (avatar)
  879. [UIImagePNGRepresentation(avatar) writeToFile:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] atomically:YES];
  880. else
  881. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] error:nil];
  882. dispatch_async(dispatch_get_main_queue(), ^{
  883. [[NSNotificationCenter defaultCenter] postNotificationName:@"changeUserProfile" object:nil];
  884. });
  885. });
  886. }
  887. #pragma --------------------------------------------------------------------------------------------
  888. #pragma mark ==== Capabilities ====
  889. #pragma --------------------------------------------------------------------------------------------
  890. - (void)getCapabilitiesOfServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  891. {
  892. // Change Theming color
  893. [app settingThemingColorBrand];
  894. if (errorCode == 401)
  895. [self changePasswordAccount];
  896. }
  897. - (void)getCapabilitiesOfServerSuccess:(OCCapabilities *)capabilities
  898. {
  899. // Update capabilities db
  900. [[NCManageDatabase sharedInstance] addCapabilities:capabilities];
  901. // ------ THEMING -----------------------------------------------------------------------
  902. // Download Theming Background & Change Theming color
  903. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  904. if ([NCBrandOptions sharedInstance].use_themingBackground == YES) {
  905. UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  906. if (themingBackground)
  907. [UIImagePNGRepresentation(themingBackground) writeToFile:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] atomically:YES];
  908. else
  909. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] error:nil];
  910. }
  911. dispatch_async(dispatch_get_main_queue(), ^{
  912. [app settingThemingColorBrand];
  913. });
  914. });
  915. // ------ SEARCH ------------------------------------------------------------------------
  916. // Search bar if change version
  917. if ([[NCManageDatabase sharedInstance] getServerVersion] != capabilities.versionMajor) {
  918. [self cancelSearchBar];
  919. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  920. if (capabilities.versionMajor >= 12) {
  921. if (_isRoot)
  922. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_all_folders_",nil);
  923. else
  924. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_sub_folder_",nil);
  925. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),self.searchController.searchBar.placeholder, nil];
  926. } else {
  927. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_this_folder_",nil);
  928. self.searchController.searchBar.scopeButtonTitles = nil;
  929. }
  930. _depth = @"0";
  931. });
  932. }
  933. // ------ GET SERVICE SERVER ------------------------------------------------------------
  934. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  935. // Read External Sites
  936. if (capabilities.isExternalSitesServerEnabled) {
  937. metadataNet.action = actionGetExternalSitesServer;
  938. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  939. }
  940. // Read Share
  941. if (capabilities.isFilesSharingAPIEnabled) {
  942. [app.sharesID removeAllObjects];
  943. metadataNet.action = actionReadShareServer;
  944. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  945. }
  946. // Read Notification
  947. metadataNet.action = actionGetNotificationServer;
  948. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  949. // Read User Profile
  950. metadataNet.action = actionGetUserProfile;
  951. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  952. // Read Activity
  953. metadataNet.action = actionGetActivityServer;
  954. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  955. }
  956. #pragma mark -
  957. #pragma --------------------------------------------------------------------------------------------
  958. #pragma mark ==== Request Server Information ====
  959. #pragma --------------------------------------------------------------------------------------------
  960. - (void)requestServerCapabilities
  961. {
  962. // test
  963. if (app.activeAccount.length == 0)
  964. return;
  965. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  966. metadataNet.action = actionGetCapabilities;
  967. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  968. }
  969. #pragma mark -
  970. #pragma --------------------------------------------------------------------------------------------
  971. #pragma mark ==== Download Thumbnail Delegate ====
  972. #pragma --------------------------------------------------------------------------------------------
  973. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  974. {
  975. __block CCCellMain *cell;
  976. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  977. if (indexPath && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]]) {
  978. cell = [self.tableView cellForRowAtIndexPath:indexPath];
  979. cell.fileImageView.image = [app.icoImagesCache objectForKey:metadataNet.fileID];
  980. if (cell.fileImageView.image == nil) {
  981. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  982. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]];
  983. [app.icoImagesCache setObject:image forKey:metadataNet.fileID];
  984. });
  985. }
  986. }
  987. }
  988. #pragma --------------------------------------------------------------------------------------------
  989. #pragma mark ==== Download ====
  990. #pragma --------------------------------------------------------------------------------------------
  991. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  992. {
  993. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  994. // File do not exists on server, remove in local
  995. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  996. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID] error:nil];
  997. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID] error:nil];
  998. if (metadata.directory && serverUrl) {
  999. NSString *dirForDelete = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileNameData];
  1000. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:dirForDelete];
  1001. }
  1002. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1003. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1004. }
  1005. if ([selector isEqualToString:selectorLoadViewImage]) {
  1006. dispatch_async(dispatch_get_main_queue(), ^{
  1007. // Updating Detail
  1008. if (app.activeDetail)
  1009. [app.activeDetail downloadPhotoBrowserFailure:errorCode];
  1010. // Updating Photos
  1011. if (app.activePhotosCameraUpload)
  1012. [app.activePhotosCameraUpload downloadFileFailure:errorCode];
  1013. });
  1014. } else {
  1015. if (errorCode != kCFURLErrorCancelled)
  1016. [app messageNotification:@"_download_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1017. }
  1018. [self reloadDatasource:serverUrl fileID:fileID selector:selector];
  1019. }
  1020. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1021. {
  1022. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1023. if (metadata == nil) return;
  1024. // Download
  1025. if ([selector isEqualToString:selectorDownloadFile]) {
  1026. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1027. }
  1028. // Synchronized
  1029. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  1030. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1031. }
  1032. // add Favorite
  1033. if ([selector isEqualToString:selectorAddFavorite]) {
  1034. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  1035. }
  1036. // encrypted file
  1037. if ([selector isEqualToString:selectorEncryptFile]) {
  1038. [self encryptedFile:metadata];
  1039. }
  1040. // decrypted file
  1041. if ([selector isEqualToString:selectorDecryptFile]) {
  1042. [self decryptedFile:metadata];
  1043. }
  1044. // open View File
  1045. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1046. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1047. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  1048. [self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  1049. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  1050. selector = selectorOpenIn;
  1051. } else {
  1052. _metadata = metadata;
  1053. if ([self shouldPerformSegue])
  1054. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  1055. }
  1056. }
  1057. // addLocal
  1058. if ([selector isEqualToString:selectorAddLocal]) {
  1059. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  1060. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  1061. [CCGraphics saveIcoWithEtag:metadata.fileNamePrint image:image writeToFile:nil copy:YES move:NO fromPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/.%@.ico", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  1062. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  1063. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1064. }
  1065. // Open with...
  1066. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1067. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1068. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1069. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1070. NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint]];
  1071. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  1072. _docController.delegate = self;
  1073. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  1074. }
  1075. // Save to Photo Album
  1076. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1077. NSString *file = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1078. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  1079. // evitiamo il rimando photo
  1080. [[NCManageDatabase sharedInstance] setAccountCameraUploadDateAssetType:PHAssetMediaTypeImage assetDate:[NSDate date]];
  1081. UIImage *image = [UIImage imageWithContentsOfFile:file];
  1082. if (image)
  1083. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1084. else
  1085. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1086. }
  1087. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  1088. // we avoid the cross-reference video
  1089. [[NCManageDatabase sharedInstance] setAccountCameraUploadDateAssetType:PHAssetMediaTypeVideo assetDate:[NSDate date]];
  1090. [[NSFileManager defaultManager] linkItemAtPath:file toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1091. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint])) {
  1092. UISaveVideoAtPathToSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint], self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1093. } else {
  1094. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1095. }
  1096. }
  1097. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1098. }
  1099. // Copy File
  1100. if ([selector isEqualToString:selectorLoadCopy]) {
  1101. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1102. [self copyFileToPasteboard:metadata];
  1103. }
  1104. // download and view a template
  1105. if ([selector isEqualToString:selectorLoadModelView]) {
  1106. metadata = [CCUtility insertInformationPlist:metadata directoryUser:app.directoryUser];
  1107. [[NCManageDatabase sharedInstance] updateMetadata:metadata activeUrl:app.activeUrl];
  1108. // se è un template aggiorniamo anche nel FileSystem
  1109. if ([metadata.type isEqualToString: k_metadataType_template]) {
  1110. [[NCManageDatabase sharedInstance] setLocalFileWithFileID:metadata.fileID date:metadata.date exifDate:nil exifLatitude:nil exifLongitude:nil fileName:nil fileNamePrint:metadata.fileNamePrint];
  1111. }
  1112. [self openModel:metadata.model isNew:false];
  1113. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1114. }
  1115. //download file plist
  1116. if ([selector isEqualToString:selectorLoadPlist]) {
  1117. metadata = [CCUtility insertInformationPlist:metadata directoryUser:app.directoryUser];
  1118. [[NCManageDatabase sharedInstance] updateMetadata:metadata activeUrl:app.activeUrl];
  1119. // se è un template aggiorniamo anche nel FileSystem
  1120. if ([metadata.type isEqualToString: k_metadataType_template]) {
  1121. [[NCManageDatabase sharedInstance] setLocalFileWithFileID:metadata.fileID date:metadata.date exifDate:nil exifLatitude:nil exifLongitude:nil fileName:nil fileNamePrint:metadata.fileNamePrint];
  1122. }
  1123. long countSelectorLoadPlist = 0;
  1124. for (NSOperation *operation in [app.netQueue operations]) {
  1125. if ([((OCnetworking *)operation).metadataNet.selector isEqualToString:selectorLoadPlist])
  1126. countSelectorLoadPlist++;
  1127. }
  1128. if ((countSelectorLoadPlist == 0 || countSelectorLoadPlist % k_maxConcurrentOperation == 0) && [metadata.directoryID isEqualToString:[[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl]]) {
  1129. dispatch_async(dispatch_get_main_queue(), ^{
  1130. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1131. });
  1132. }
  1133. }
  1134. //selectorLoadViewImage
  1135. if ([selector isEqualToString:selectorLoadViewImage]) {
  1136. dispatch_async(dispatch_get_main_queue(), ^{
  1137. // Detail
  1138. if (app.activeDetail)
  1139. [app.activeDetail downloadPhotoBrowserSuccess:metadata selector:selector];
  1140. // Photos
  1141. if (app.activePhotosCameraUpload)
  1142. [app.activePhotosCameraUpload downloadFileSuccess:metadata];
  1143. });
  1144. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1145. }
  1146. // if exists postselector call self with selectorPost
  1147. if ([selectorPost length] > 0)
  1148. [self downloadFileSuccess:fileID serverUrl:serverUrl selector:selectorPost selectorPost:nil];
  1149. }
  1150. - (void)downloadSelectedFiles
  1151. {
  1152. NSLog(@"[LOG] Start download selected files ...");
  1153. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1154. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1155. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1156. for (tableMetadata *metadata in selectedMetadatas) {
  1157. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file]) {
  1158. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1159. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDownloadFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1160. }
  1161. }
  1162. [_hud hideHud];
  1163. });
  1164. [self tableViewSelect:NO];
  1165. }
  1166. - (void)downloadPlist:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1167. {
  1168. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", app.activeAccount, directoryID] sorted:nil ascending:NO];
  1169. for (tableMetadata *metadata in metadatas) {
  1170. if ([CCUtility isCryptoPlistString:metadata.fileName] && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName]] == NO && [metadata.session length] == 0) {
  1171. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1172. metadataNet.action = actionDownloadFile;
  1173. metadataNet.downloadData = NO;
  1174. metadataNet.downloadPlist = YES;
  1175. metadataNet.fileID = metadata.fileID;
  1176. metadataNet.selector = selectorLoadPlist;
  1177. metadataNet.serverUrl = serverUrl;
  1178. metadataNet.session = k_download_session_foreground;
  1179. metadataNet.taskStatus = k_taskStatusResume;
  1180. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1181. }
  1182. }
  1183. }
  1184. #pragma --------------------------------------------------------------------------------------------
  1185. #pragma mark ===== Upload new Photos/Videos =====
  1186. #pragma --------------------------------------------------------------------------------------------
  1187. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1188. {
  1189. // Automatic upload All
  1190. if([selector isEqualToString:selectorUploadAutomaticAll])
  1191. [app performSelectorOnMainThread:@selector(loadAutomaticUpload) withObject:nil waitUntilDone:NO];
  1192. // Read File test do not exists
  1193. if (errorCode == k_CCErrorFileUploadNotFound && fileID) {
  1194. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1195. // reUpload
  1196. if (metadata)
  1197. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1198. }
  1199. // Print error
  1200. else if (errorCode != kCFURLErrorCancelled && errorCode != 403) {
  1201. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1202. }
  1203. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1204. }
  1205. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1206. {
  1207. // Automatic upload All
  1208. if([selector isEqualToString:selectorUploadAutomaticAll])
  1209. [app performSelectorOnMainThread:@selector(loadAutomaticUpload) withObject:nil waitUntilDone:NO];
  1210. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1211. [self readFolderWithForced:YES serverUrl:serverUrl];
  1212. } else {
  1213. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1214. }
  1215. }
  1216. //
  1217. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1218. //
  1219. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1220. {
  1221. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1222. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:cryptated], [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1223. });
  1224. }
  1225. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1226. {
  1227. NSArray *assets = [arguments objectAtIndex:0];
  1228. NSString *serverUrl = [arguments objectAtIndex:1];
  1229. BOOL cryptated = [[arguments objectAtIndex:2] boolValue];
  1230. BOOL useSubFolder = [[arguments objectAtIndex:3] boolValue];
  1231. NSString *session = [arguments objectAtIndex:4];
  1232. NSString *folderPhotos = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderPathWithActiveUrl:app.activeUrl];
  1233. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  1234. // Create the folder for Photos & if request the subfolders
  1235. if (![app createFolderSubFolderAutomaticUploadFolderPhotos:folderPhotos useSubFolder:useSubFolder assets:assets selector:selectorUploadFile])
  1236. return;
  1237. NSLog(@"[LOG] Asset N. %lu", (unsigned long)[assets count]);
  1238. for (PHAsset *asset in assets) {
  1239. NSString *fileName = [CCUtility createFileNameFromAsset:asset key: k_keyFileNameMask];
  1240. NSDate *assetDate = asset.creationDate;
  1241. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1242. // Create serverUrl if use sub folder
  1243. if (useSubFolder) {
  1244. [formatter setDateFormat:@"yyyy"];
  1245. NSString *yearString = [formatter stringFromDate:assetDate];
  1246. [formatter setDateFormat:@"MM"];
  1247. NSString *monthString = [formatter stringFromDate:assetDate];
  1248. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", folderPhotos, yearString, monthString];
  1249. }
  1250. // Check if is in upload
  1251. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@ AND session != ''", app.activeAccount, directoryID, fileName];
  1252. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1253. if ([isRecordInSessions count] > 0) {
  1254. // next upload
  1255. continue;
  1256. } else {
  1257. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1258. metadataNet.action = actionReadFile;
  1259. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1260. metadataNet.cryptated = cryptated;
  1261. metadataNet.fileName = fileName;
  1262. metadataNet.priority = NSOperationQueuePriorityNormal;
  1263. metadataNet.session = session;
  1264. metadataNet.selector = selectorReadFileUploadFile;
  1265. metadataNet.serverUrl = serverUrl;
  1266. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1267. }
  1268. }
  1269. }
  1270. #pragma --------------------------------------------------------------------------------------------
  1271. #pragma mark ==== Read File ====
  1272. #pragma --------------------------------------------------------------------------------------------
  1273. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1274. {
  1275. // UploadFile
  1276. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1277. // File not exists
  1278. if (errorCode == 404) {
  1279. metadataNet.action = actionUploadAsset;
  1280. metadataNet.errorCode = 0;
  1281. metadataNet.selector = selectorUploadFile;
  1282. metadataNet.selectorPost = nil;
  1283. metadataNet.taskStatus = k_taskStatusResume;
  1284. if ([metadataNet.session containsString:@"wwan"])
  1285. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1286. else
  1287. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1288. } else {
  1289. // error ho many retry befor notification and go to on next asses
  1290. if (metadataNet.errorRetry < 3) {
  1291. // Retry read file
  1292. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1293. } else {
  1294. // STOP check file, view message error
  1295. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1296. }
  1297. }
  1298. }
  1299. }
  1300. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata
  1301. {
  1302. // UploadFile
  1303. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1304. metadataNet.action = actionUploadAsset;
  1305. metadataNet.errorCode = 403; // File exists 403 Forbidden
  1306. metadataNet.selector = selectorUploadFile;
  1307. metadataNet.selectorPost = nil;
  1308. metadataNet.taskStatus = k_taskStatusResume;
  1309. if ([metadataNet.session containsString:@"wwan"])
  1310. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1311. else
  1312. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1313. }
  1314. }
  1315. #pragma --------------------------------------------------------------------------------------------
  1316. #pragma mark ==== Read Folder ====
  1317. #pragma --------------------------------------------------------------------------------------------
  1318. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1319. {
  1320. // verify active user
  1321. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1322. [_hud hideHud];
  1323. [_refreshControl endRefreshing];
  1324. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1325. if (message && [record.account isEqualToString:metadataNet.account])
  1326. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1327. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1328. if (errorCode == 401)
  1329. [self changePasswordAccount];
  1330. }
  1331. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet permissions:(NSString *)permissions fileID:(NSString *)fileID metadatas:(NSArray *)metadatas
  1332. {
  1333. // verify active user
  1334. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1335. if (![record.account isEqualToString:metadataNet.account])
  1336. return;
  1337. // save father e update permission
  1338. if(!_isSearchMode)
  1339. _fatherPermission = permissions;
  1340. NSArray *recordsInSessions;
  1341. if (_isSearchMode) {
  1342. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", metadataNet.account] sorted:nil ascending:NO];
  1343. } else {
  1344. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:metadataNet.serverUrl serverUrlTo:nil fileID:fileID];
  1345. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", metadataNet.account, metadataNet.directoryID]];
  1346. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session != ''", metadataNet.account, metadataNet.directoryID] sorted:nil ascending:NO];
  1347. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithDirectoryID:metadataNet.directoryID];
  1348. }
  1349. for (tableMetadata *metadata in metadatas) {
  1350. // type of file
  1351. NSInteger typeFilename = [CCUtility getTypeFileName:metadata.fileName];
  1352. // if crypto do not insert
  1353. if (typeFilename == k_metadataTypeFilenameCrypto) continue;
  1354. // verify if the record encrypted has plist + crypto
  1355. if (typeFilename == k_metadataTypeFilenamePlist && metadata.directory == NO) {
  1356. BOOL isCryptoComplete = NO;
  1357. NSString *fileNameCrypto = [CCUtility trasformedFileNamePlistInCrypto:metadata.fileName];
  1358. for (tableMetadata *completeMetadata in metadatas) {
  1359. if (completeMetadata.cryptated == NO) continue;
  1360. else if ([completeMetadata.fileName isEqualToString:fileNameCrypto]) {
  1361. isCryptoComplete = YES;
  1362. break;
  1363. }
  1364. }
  1365. if (isCryptoComplete == NO) continue;
  1366. }
  1367. // verify if the record is in download/upload progress
  1368. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1369. tableMetadata *metadataTransfer = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@", app.activeAccount, metadataNet.directoryID, metadata.fileName]];
  1370. // is in Download or Upload
  1371. if ([metadataTransfer.session containsString:@"upload"] || [metadataTransfer.session containsString:@"download"]) {
  1372. continue;
  1373. }
  1374. }
  1375. // end test, insert in Database
  1376. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata activeUrl:app.activeUrl];
  1377. }
  1378. // read plist
  1379. if (!_isSearchMode)
  1380. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1381. // File is changed ??
  1382. if (!_isSearchMode)
  1383. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatas serverUrl:metadataNet.serverUrl account:app.activeAccount withDownload:NO];
  1384. // Search Mode
  1385. if (_isSearchMode)
  1386. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1387. // this is the same directory
  1388. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1389. // reload
  1390. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1391. // stoprefresh
  1392. [_refreshControl endRefreshing];
  1393. // Enable change user
  1394. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1395. [_hud hideHud];
  1396. }
  1397. }
  1398. - (void)readFolderWithForced:(BOOL)forced serverUrl:(NSString *)serverUrl
  1399. {
  1400. // init control
  1401. if (!serverUrl || !app.activeAccount)
  1402. return;
  1403. // Search Mode
  1404. if (_isSearchMode) {
  1405. if (forced) {
  1406. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1407. _searchFileName = @""; // forced reload searchg
  1408. }
  1409. [self updateSearchResultsForSearchController:self.searchController];
  1410. return;
  1411. }
  1412. BOOL isDirectoryOutOfDate = true;
  1413. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", serverUrl]];
  1414. if (directory.dateReadDirectory) {
  1415. // Is Directory Out Of Date ?
  1416. NSDateComponents *dateComponents = [NSDateComponents new];
  1417. [dateComponents setWeekday:k_dayForceReadFolder];
  1418. NSCalendar *calendar = [NSCalendar currentCalendar];
  1419. NSDate *datePlus = [calendar dateByAddingComponents:dateComponents toDate:directory.dateReadDirectory options:0];
  1420. NSDate *now = [NSDate date];
  1421. // usa la Cache se richiesto e se la data è entro X giorni dall'ultima volta che l'hai letta.
  1422. if ([now compare:datePlus] == NSOrderedDescending)
  1423. isDirectoryOutOfDate = true;
  1424. else
  1425. isDirectoryOutOfDate = false;
  1426. }
  1427. if (isDirectoryOutOfDate || forced) {
  1428. if (_refreshControl.isRefreshing == NO)
  1429. [_hud visibleIndeterminateHud];
  1430. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1431. metadataNet.action = actionReadFolder;
  1432. metadataNet.date = [NSDate date];
  1433. metadataNet.directoryID = directory.directoryID;
  1434. metadataNet.priority = NSOperationQueuePriorityHigh;
  1435. metadataNet.selector = selectorReadFolder;
  1436. metadataNet.serverUrl = serverUrl;
  1437. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1438. }
  1439. }
  1440. #pragma mark -
  1441. #pragma --------------------------------------------------------------------------------------------
  1442. #pragma mark ===== Search =====
  1443. #pragma --------------------------------------------------------------------------------------------
  1444. -(void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1445. {
  1446. _isSearchMode = YES;
  1447. [self deleteRefreshControl];
  1448. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1449. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1450. _searchFileName = fileName;
  1451. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12 && ![_depth isEqualToString:@"0"]) {
  1452. [[CCActions sharedInstance] search:_serverUrl fileName:_searchFileName depth:_depth delegate:self];
  1453. _noFilesSearchTitle = @"";
  1454. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1455. [self.tableView reloadEmptyDataSet];
  1456. } else {
  1457. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1458. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID = %@ AND account = %@ AND fileNamePrint CONTAINS[cd] %@", directoryID, app.activeAccount, fileName];
  1459. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1460. [_searchResultMetadatas removeAllObjects];
  1461. for (tableMetadata *record in records)
  1462. [_searchResultMetadatas addObject:record];
  1463. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1464. metadataNet.account = app.activeAccount;
  1465. metadataNet.action = actionUploadTemplate;
  1466. metadataNet.directoryID = directoryID;
  1467. metadataNet.selector = selectorSearch;
  1468. metadataNet.serverUrl = _serverUrl;
  1469. [self readFolderSuccess:metadataNet permissions:@"" fileID:@"" metadatas:_searchResultMetadatas];
  1470. }
  1471. }
  1472. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1473. [self reloadDatasource];
  1474. }
  1475. }
  1476. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1477. {
  1478. [self cancelSearchBar];
  1479. [self readFolderWithForced:NO serverUrl:_serverUrl];
  1480. }
  1481. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1482. {
  1483. _searchFileName = @"";
  1484. if (message)
  1485. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1486. }
  1487. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1488. {
  1489. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1490. [self readFolderSuccess:metadataNet permissions:nil fileID:nil metadatas:metadatas];
  1491. }
  1492. - (void)cancelSearchBar
  1493. {
  1494. if (self.searchController.active) {
  1495. [self.searchController setActive:NO];
  1496. [self createRefreshControl];
  1497. _isSearchMode = NO;
  1498. _searchFileName = @"";
  1499. _dateReadDataSource = nil;
  1500. _searchResultMetadatas = [NSMutableArray new];
  1501. [self reloadDatasource];
  1502. }
  1503. }
  1504. - (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope
  1505. {
  1506. NSString *title = [self.searchController.searchBar.scopeButtonTitles objectAtIndex:selectedScope];
  1507. self.searchController.searchBar.placeholder = title;
  1508. if ([title isEqualToString:NSLocalizedString(@"_search_this_folder_",nil)])
  1509. _depth = @"0";
  1510. if ([title isEqualToString:NSLocalizedString(@"_search_sub_folder_",nil)])
  1511. _depth = @"1";
  1512. if ([title isEqualToString:NSLocalizedString(@"_search_all_folders_",nil)])
  1513. _depth = @"infinity";
  1514. _searchFileName = @"";
  1515. [self updateSearchResultsForSearchController:self.searchController];
  1516. }
  1517. #pragma mark -
  1518. #pragma --------------------------------------------------------------------------------------------
  1519. #pragma mark ===== Delete File or Folder =====
  1520. #pragma --------------------------------------------------------------------------------------------
  1521. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1522. {
  1523. [self deleteFileOrFolderSuccess:metadataNet];
  1524. }
  1525. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1526. {
  1527. [_queueSelector removeObject:metadataNet.selector];
  1528. if ([_queueSelector count] == 0) {
  1529. [_hud hideHud];
  1530. if (_isSearchMode)
  1531. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1532. else
  1533. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  1534. // next
  1535. if ([_selectedMetadatas count] > 0) {
  1536. [_selectedMetadatas removeObjectAtIndex:0];
  1537. if ([_selectedMetadatas count] > 0)
  1538. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1539. }
  1540. }
  1541. }
  1542. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1543. {
  1544. if (metadata.cryptated) {
  1545. [_queueSelector addObject:selectorDeleteCrypto];
  1546. [_queueSelector addObject:selectorDeletePlist];
  1547. } else {
  1548. [_queueSelector addObject:selectorDelete];
  1549. }
  1550. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1551. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1552. }
  1553. - (void)deleteSelectionFile
  1554. {
  1555. [_selectedMetadatas removeAllObjects];
  1556. [_queueSelector removeAllObjects];
  1557. _selectedMetadatas = [[NSMutableArray alloc] initWithArray: [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]]];
  1558. _numSelectedMetadatas = [_selectedMetadatas count];
  1559. if ([_selectedMetadatas count] > 0)
  1560. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1561. [self tableViewSelect:NO];
  1562. }
  1563. - (void)deleteFile
  1564. {
  1565. [_selectedMetadatas removeAllObjects];
  1566. [_queueSelector removeAllObjects];
  1567. _numSelectedMetadatas = 1;
  1568. [_selectedMetadatas addObject:_metadata];
  1569. if ([_selectedMetadatas count] > 0)
  1570. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1571. [self tableViewSelect:NO];
  1572. }
  1573. #pragma --------------------------------------------------------------------------------------------
  1574. #pragma mark ===== Rename / Move =====
  1575. #pragma --------------------------------------------------------------------------------------------
  1576. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1577. {
  1578. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1579. }
  1580. - (void)renameFile:(tableMetadata *)metadata fileName:(NSString *)fileName
  1581. {
  1582. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1583. }
  1584. - (void)renameNote:(tableMetadata *)metadata fileName:(NSString *)fileName
  1585. {
  1586. CCTemplates *templates = [[CCTemplates alloc] init];
  1587. NSMutableDictionary *field = [[CCCrypto sharedManager] getDictionaryEncrypted:metadata.fileName uuid:metadata.uuid isLocal:NO directoryUser:app.directoryUser];
  1588. NSString *fileNameModel = [templates salvaNote:[field objectForKey:@"note"] titolo:fileName fileName:metadata.fileName uuid:metadata.uuid];
  1589. if (fileNameModel) {
  1590. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1591. metadataNet.action = actionUploadTemplate;
  1592. metadataNet.fileName = [CCUtility trasformedFileNamePlistInCrypto:fileNameModel];
  1593. metadataNet.fileNamePrint = fileName;
  1594. metadataNet.rev = metadata.rev;
  1595. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1596. metadataNet.session = k_upload_session_foreground;
  1597. metadataNet.taskStatus = k_taskStatusResume;
  1598. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1599. }
  1600. }
  1601. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1602. {
  1603. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1604. [_hud hideHud];
  1605. if (message)
  1606. [app messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1607. [_selectedMetadatas removeAllObjects];
  1608. [_queueSelector removeAllObjects];
  1609. }
  1610. }
  1611. - (void)moveSuccess:(CCMetadataNet *)metadataNet revTo:(NSString *)revTo
  1612. {
  1613. [_queueSelector removeObject:metadataNet.selector];
  1614. if ([_queueSelector count] == 0) {
  1615. [_hud hideHud];
  1616. NSString *fileName = [CCUtility trasformedFileNameCryptoInPlist:metadataNet.fileName];
  1617. NSString *directoryID = metadataNet.directoryID;
  1618. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1619. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1620. // FILE -> Metadata
  1621. if (metadataNet.directory == NO) {
  1622. // move metadata
  1623. //[CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1624. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1625. }
  1626. // DIRECTORY -> Directory - CCMetadata
  1627. if (metadataNet.directory == YES) {
  1628. // delete all dir / subdir
  1629. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName]];
  1630. // move metadata
  1631. //[CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1632. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1633. // Add new directory
  1634. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1635. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:@""];
  1636. }
  1637. // reload Datasource
  1638. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1639. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1640. else
  1641. [self reloadDatasource];
  1642. // Next file
  1643. [_selectedMetadatas removeObjectAtIndex:0];
  1644. [self performSelectorOnMainThread:@selector(moveFileOrFolder:) withObject:metadataNet.serverUrlTo waitUntilDone:NO];
  1645. }
  1646. }
  1647. - (void)moveFileOrFolder:(NSString *)serverUrlTo
  1648. {
  1649. if ([_selectedMetadatas count] > 0) {
  1650. tableMetadata *metadata = [_selectedMetadatas objectAtIndex:0];
  1651. // Plain
  1652. if (metadata.cryptated == NO) {
  1653. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withPassword:app.activePassword withUrl:app.activeUrl isCryptoCloudMode:NO];
  1654. NSError *error = [ocNetworking readFileSync:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName]];
  1655. if(!error) {
  1656. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1657. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1658. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1659. }];
  1660. [alert addAction:ok];
  1661. [self presentViewController:alert animated:YES completion:nil];
  1662. });
  1663. return;
  1664. }
  1665. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1666. metadataNet.action = actionMoveFileOrFolder;
  1667. metadataNet.directory = metadata.directory;
  1668. metadataNet.fileID = metadata.fileID;
  1669. metadataNet.directoryID = metadata.directoryID;
  1670. metadataNet.directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1671. metadataNet.fileName = metadata.fileName;
  1672. metadataNet.fileNamePrint = metadataNet.fileNamePrint;
  1673. metadataNet.fileNameTo = metadata.fileName;
  1674. metadataNet.rev = metadata.rev;
  1675. metadataNet.selector = selectorMove;
  1676. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1677. metadataNet.serverUrlTo = serverUrlTo;
  1678. [_queueSelector addObject:metadataNet.selector];
  1679. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1680. }
  1681. // cyptated
  1682. if (metadata.cryptated == YES) {
  1683. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1684. metadataNet.action = actionMoveFileOrFolder;
  1685. metadataNet.directory = metadata.directory;
  1686. metadataNet.fileID = metadata.fileID;
  1687. metadataNet.directoryID = metadata.directoryID;
  1688. metadataNet.directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1689. metadataNet.fileNamePrint = metadata.fileNamePrint;
  1690. metadataNet.rev = metadata.rev;
  1691. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1692. metadataNet.serverUrlTo = serverUrlTo;
  1693. // data
  1694. metadataNet.fileName = metadata.fileNameData;
  1695. metadataNet.fileNameTo = metadata.fileNameData;
  1696. metadataNet.selector = selectorMoveCrypto;
  1697. [_queueSelector addObject:metadataNet.selector];
  1698. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1699. // plist
  1700. metadataNet.fileName = metadata.fileName;
  1701. metadataNet.fileNameTo = metadata.fileName;
  1702. metadataNet.selector = selectorMovePlist;
  1703. [_queueSelector addObject:metadataNet.selector];
  1704. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1705. }
  1706. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), _numSelectedMetadatas - [_selectedMetadatas count] + 1, _numSelectedMetadatas] mode:MBProgressHUDModeIndeterminate color:nil];
  1707. }
  1708. }
  1709. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title selectedMetadatas:(NSArray *)selectedMetadatas
  1710. {
  1711. [_selectedMetadatas removeAllObjects];
  1712. [_queueSelector removeAllObjects];
  1713. _selectedMetadatas = [[NSMutableArray alloc] initWithArray:selectedMetadatas];
  1714. _numSelectedMetadatas = [_selectedMetadatas count];
  1715. [self performSelectorOnMainThread:@selector(moveFileOrFolder:) withObject:serverUrlTo waitUntilDone:NO];
  1716. [self tableViewSelect:NO];
  1717. }
  1718. - (void)moveOpenWindow:(NSArray *)indexPaths
  1719. {
  1720. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1721. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1722. viewController.delegate = self;
  1723. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1724. viewController.selectedMetadatas = [self getMetadatasFromSelectedRows:indexPaths];
  1725. viewController.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  1726. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1727. viewController.tintColorTitle = [NCBrandColor sharedInstance].navigationBarText;
  1728. viewController.networkingOperationQueue = app.netQueue;
  1729. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1730. [self presentViewController:navigationController animated:YES completion:nil];
  1731. }
  1732. #pragma --------------------------------------------------------------------------------------------
  1733. #pragma mark ===== Create folder =====
  1734. #pragma --------------------------------------------------------------------------------------------
  1735. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1736. {
  1737. [_hud hideHud];
  1738. if (message)
  1739. [app messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1740. }
  1741. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1742. {
  1743. [_hud hideHud];
  1744. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1745. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:@""];
  1746. // Load Folder or the Datasource
  1747. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced]) {
  1748. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1749. } else {
  1750. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  1751. }
  1752. }
  1753. - (void)createFolder:(NSString *)fileNameFolder folderCameraUpload:(BOOL)folderCameraUpload
  1754. {
  1755. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1756. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1757. if (![fileNameFolder length]) return;
  1758. if (folderCameraUpload) metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderPathWithActiveUrl:app.activeUrl];
  1759. else metadataNet.serverUrl = _serverUrl;
  1760. metadataNet.action = actionCreateFolder;
  1761. if (folderCameraUpload)
  1762. metadataNet.options = @"folderCameraUpload";
  1763. metadataNet.fileName = fileNameFolder;
  1764. metadataNet.selector = selectorCreateFolder;
  1765. metadataNet.selectorPost = selectorReadFolderForced;
  1766. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1767. if (!folderCameraUpload)
  1768. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1769. }
  1770. - (void)createFolderEncrypted:(NSString *)fileNameFolder
  1771. {
  1772. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1773. NSString *fileNamePlist;
  1774. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1775. if (![fileNameFolder length]) return;
  1776. NSString *title = [AESCrypt encrypt:fileNameFolder password:[[CCCrypto sharedManager] getKeyPasscode:[CCUtility getUUID]]];
  1777. fileNamePlist = [[CCCrypto sharedManager] createFilenameEncryptor:fileNameFolder uuid:[CCUtility getUUID]];
  1778. [[CCCrypto sharedManager] createFilePlist:[NSTemporaryDirectory() stringByAppendingString:fileNamePlist] title:title len:0 directory:true uuid:[CCUtility getUUID] nameCurrentDevice:[CCUtility getNameCurrentDevice] icon:@""];
  1779. // Create folder
  1780. metadataNet.action = actionCreateFolder;
  1781. metadataNet.fileName = fileNamePlist;
  1782. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1783. metadataNet.selector = selectorCreateFolder;
  1784. metadataNet.serverUrl = _serverUrl;
  1785. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1786. // upload plist file
  1787. metadataNet.action = actionUploadOnlyPlist;
  1788. metadataNet.fileName = [fileNamePlist stringByAppendingString:@".plist"];
  1789. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1790. metadataNet.selectorPost = selectorReadFolderForced;
  1791. metadataNet.serverUrl = _serverUrl;
  1792. metadataNet.session = k_upload_session_foreground;
  1793. metadataNet.taskStatus = k_taskStatusResume;
  1794. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1795. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1796. }
  1797. - (void)createFolderCameraUpload
  1798. {
  1799. NSString *cameraFolderName = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderName];
  1800. [self createFolder:cameraFolderName folderCameraUpload:YES];
  1801. }
  1802. #pragma --------------------------------------------------------------------------------------------
  1803. #pragma mark ===== Encrypted / Decrypted Folder =====
  1804. #pragma --------------------------------------------------------------------------------------------
  1805. - (void)encyptedDecryptedFolder
  1806. {
  1807. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  1808. if (_metadata.cryptated) {
  1809. // DECRYPTED
  1810. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1811. //-------------------------- RENAME -------------------------------------------//
  1812. metadataNet.action = actionMoveFileOrFolder;
  1813. metadataNet.fileID = _metadata.fileID;
  1814. metadataNet.fileName = _metadata.fileNameData;
  1815. metadataNet.fileNameTo = _metadata.fileNamePrint;
  1816. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1817. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1818. metadataNet.selector = selectorRename;
  1819. metadataNet.serverUrl = serverUrl;
  1820. metadataNet.serverUrlTo = serverUrl;
  1821. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1822. //-------------------------- DELETE -------------------------------------------//
  1823. metadataNet.action = actionDeleteFileDirectory;
  1824. metadataNet.fileID = _metadata.fileID;
  1825. metadataNet.fileName = _metadata.fileName;
  1826. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1827. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1828. metadataNet.selector = selectorDeletePlist;
  1829. metadataNet.selectorPost = selectorReadFolderForced;
  1830. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1831. } else {
  1832. // ENCRYPTED
  1833. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1834. // Create File Plist
  1835. NSString *fileNameCrypto = [[CCCrypto sharedManager] createFileDirectoryPlist:_metadata];
  1836. //-------------------------- RENAME -------------------------------------------//
  1837. metadataNet.action = actionMoveFileOrFolder;
  1838. metadataNet.fileID = _metadata.fileID;
  1839. metadataNet.fileName = _metadata.fileName;
  1840. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1841. metadataNet.fileNameTo = fileNameCrypto;
  1842. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1843. metadataNet.selector = selectorRename;
  1844. metadataNet.serverUrl = serverUrl;
  1845. metadataNet.serverUrlTo = serverUrl;
  1846. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1847. //-------------------------- UPLOAD -------------------------------------------//
  1848. metadataNet.action = actionUploadOnlyPlist;
  1849. metadataNet.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  1850. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1851. metadataNet.selectorPost = selectorReadFolderForced;
  1852. metadataNet.serverUrl = serverUrl;
  1853. metadataNet.session = k_upload_session_foreground;
  1854. metadataNet.taskStatus = k_taskStatusResume;
  1855. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1856. }
  1857. }
  1858. #pragma --------------------------------------------------------------------------------------------
  1859. #pragma mark ===== Encrypted/Decrypted File =====
  1860. #pragma --------------------------------------------------------------------------------------------
  1861. - (void)encryptedSelectedFiles
  1862. {
  1863. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1864. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1865. for (tableMetadata *metadata in selectedMetadatas) {
  1866. if (metadata.cryptated == NO && metadata.directory == NO)
  1867. [metadatas addObject:metadata];
  1868. }
  1869. if ([metadatas count] > 0) {
  1870. NSLog(@"[LOG] Start encrypted selected files ...");
  1871. for (tableMetadata* metadata in metadatas) {
  1872. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1873. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorEncryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1874. }
  1875. }
  1876. [self tableViewSelect:NO];
  1877. }
  1878. - (void)decryptedSelectedFiles
  1879. {
  1880. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1881. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1882. for (tableMetadata *metadata in selectedMetadatas) {
  1883. if (metadata.cryptated == YES && metadata.directory == NO && [metadata.model length] == 0)
  1884. [metadatas addObject:metadata];
  1885. }
  1886. if ([metadatas count] > 0) {
  1887. NSLog(@"[LOG] Start decrypted selected files ...");
  1888. for (tableMetadata* metadata in metadatas) {
  1889. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1890. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDecryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1891. }
  1892. }
  1893. [self tableViewSelect:NO];
  1894. }
  1895. - (void)cmdEncryptedDecryptedFile
  1896. {
  1897. NSString *selector;
  1898. if (_metadata.cryptated == YES) selector = selectorDecryptFile;
  1899. if (_metadata.cryptated == NO) selector = selectorEncryptFile;
  1900. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  1901. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  1902. }
  1903. - (void)encryptedFile:(tableMetadata *)metadata
  1904. {
  1905. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1906. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1907. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1908. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1909. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1910. dispatch_async(dispatch_get_main_queue(), ^{
  1911. [[CCNetworking sharedNetworking] uploadFile:metadata.fileName serverUrl:serverUrl cryptated:YES onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1912. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1913. });
  1914. } else {
  1915. [app messageNotification:@"_encrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1916. }
  1917. }
  1918. - (void)decryptedFile:(tableMetadata *)metadata
  1919. {
  1920. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1921. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1922. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1923. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1924. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1925. dispatch_async(dispatch_get_main_queue(), ^{
  1926. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:serverUrl cryptated:NO onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1927. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1928. });
  1929. } else {
  1930. [app messageNotification:@"_decrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1931. }
  1932. }
  1933. #pragma --------------------------------------------------------------------------------------------
  1934. #pragma mark ===== Progress & Task Button =====
  1935. #pragma --------------------------------------------------------------------------------------------
  1936. - (void)triggerProgressTask:(NSNotification *)notification
  1937. {
  1938. NSDictionary *dict = notification.userInfo;
  1939. NSString *fileID = [dict valueForKey:@"fileID"];
  1940. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1941. BOOL cryptated = [[dict valueForKey:@"cryptated"] boolValue];
  1942. float progress = [[dict valueForKey:@"progress"] floatValue];
  1943. // Check
  1944. if (!fileID)
  1945. return;
  1946. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1947. if (![serverUrl isEqualToString:_serverUrl])
  1948. return;
  1949. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1950. if (indexPath) {
  1951. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1952. if (cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  1953. else cell.progressView.progressTintColor = [UIColor blackColor];
  1954. cell.progressView.hidden = NO;
  1955. [cell.progressView setProgress:progress];
  1956. }
  1957. if (progress == 0)
  1958. [self.navigationController cancelCCProgress];
  1959. else
  1960. [self.navigationController setCCProgressPercentage:progress*100 andTintColor: [NCBrandColor sharedInstance].navigationBarProgress];
  1961. }
  1962. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  1963. {
  1964. UITouch * touch = [[event allTouches] anyObject];
  1965. CGPoint location = [touch locationInView:self.tableView];
  1966. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  1967. if (indexPath) {
  1968. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1969. if (metadata)
  1970. [self reloadTaskButton:metadata];
  1971. }
  1972. }
  1973. - (void)reloadTaskButton:(tableMetadata *)metadata
  1974. {
  1975. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1976. __block NSURLSessionTask *findTask;
  1977. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1978. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  1979. NSString *fileID = metadata.fileID;
  1980. // DOWNLOAD
  1981. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1982. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1983. for (NSURLSessionUploadTask *task in downloadTasks)
  1984. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  1985. findTask = task;
  1986. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1987. [task cancel];
  1988. }
  1989. if (!findTask) {
  1990. dispatch_async(dispatch_get_main_queue(), ^{
  1991. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1992. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1993. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  1994. });
  1995. }
  1996. }];
  1997. }
  1998. // UPLOAD
  1999. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2000. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2001. for (NSURLSessionUploadTask *task in uploadTasks)
  2002. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2003. findTask = task;
  2004. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  2005. [task cancel];
  2006. }
  2007. if (!findTask) {
  2008. dispatch_async(dispatch_get_main_queue(), ^{
  2009. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  2010. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2011. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2012. });
  2013. }
  2014. }];
  2015. }
  2016. }
  2017. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  2018. {
  2019. UITouch * touch = [[event allTouches] anyObject];
  2020. CGPoint location = [touch locationInView:self.tableView];
  2021. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2022. if (indexPath) {
  2023. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2024. if (metadata)
  2025. [self cancelTaskButton:metadata reloadTable:YES];
  2026. }
  2027. }
  2028. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  2029. {
  2030. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2031. __block NSURLSessionTask *findTask;
  2032. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2033. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2034. NSString *fileID = metadata.fileID;
  2035. // DOWNLOAD
  2036. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  2037. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2038. for (NSURLSessionTask *task in downloadTasks)
  2039. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2040. findTask = task;
  2041. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  2042. [task cancel];
  2043. }
  2044. if (!findTask) {
  2045. dispatch_async(dispatch_get_main_queue(), ^{
  2046. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  2047. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2048. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2049. });
  2050. }
  2051. }];
  2052. }
  2053. // UPLOAD
  2054. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2055. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2056. for (NSURLSessionUploadTask *task in uploadTasks)
  2057. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2058. findTask = task;
  2059. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  2060. [task cancel];
  2061. }
  2062. if (!findTask) {
  2063. dispatch_async(dispatch_get_main_queue(), ^{
  2064. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  2065. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2066. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2067. });
  2068. }
  2069. }];
  2070. }
  2071. }
  2072. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  2073. {
  2074. UITouch * touch = [[event allTouches] anyObject];
  2075. CGPoint location = [touch locationInView:self.tableView];
  2076. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2077. if (indexPath) {
  2078. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2079. if (metadata)
  2080. [self stopTaskButton:metadata];
  2081. }
  2082. }
  2083. - (void)stopTaskButton:(tableMetadata *)metadata
  2084. {
  2085. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2086. __block NSURLSessionTask *findTask;
  2087. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2088. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2089. NSString *fileID = metadata.fileID;
  2090. // UPLOAD
  2091. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2092. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2093. for (NSURLSessionUploadTask *task in uploadTasks)
  2094. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2095. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  2096. findTask = task;
  2097. [task cancel];
  2098. }
  2099. if (!findTask) {
  2100. dispatch_async(dispatch_get_main_queue(), ^{
  2101. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  2102. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2103. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2104. });
  2105. }
  2106. }];
  2107. }
  2108. }
  2109. #pragma --------------------------------------------------------------------------------------------
  2110. #pragma mark ===== Shared =====
  2111. #pragma --------------------------------------------------------------------------------------------
  2112. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  2113. {
  2114. [_hud hideHud];
  2115. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2116. // change account ?
  2117. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  2118. if([record.account isEqualToString:metadataNet.account] == NO)
  2119. return;
  2120. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  2121. if (result) {
  2122. appDelegate.sharesLink = result[0];
  2123. appDelegate.sharesUserAndGroup = result[1];
  2124. }
  2125. if (openWindow) {
  2126. if (_shareOC) {
  2127. [_shareOC reloadData];
  2128. } else {
  2129. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2130. // Apriamo la view
  2131. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  2132. _shareOC.delegate = self;
  2133. _shareOC.metadata = metadata;
  2134. _shareOC.serverUrl = metadataNet.serverUrl;
  2135. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  2136. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  2137. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  2138. [self presentViewController:_shareOC animated:YES completion:nil];
  2139. }
  2140. }
  2141. [self tableViewReload];
  2142. }
  2143. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2144. {
  2145. [_hud hideHud];
  2146. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2147. if (_shareOC)
  2148. [_shareOC reloadData];
  2149. [self tableViewReload];
  2150. if (errorCode == 401)
  2151. [self changePasswordAccount];
  2152. }
  2153. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  2154. {
  2155. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2156. metadataNet.action = actionShare;
  2157. metadataNet.fileID = metadata.fileID;
  2158. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2159. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2160. metadataNet.password = password;
  2161. metadataNet.selector = selectorShare;
  2162. metadataNet.serverUrl = serverUrl;
  2163. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2164. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2165. }
  2166. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  2167. {
  2168. [_hud hideHud];
  2169. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2170. // rimuoviamo la condivisione da db
  2171. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  2172. if (result) {
  2173. appDelegate.sharesLink = result[0];
  2174. appDelegate.sharesUserAndGroup = result[1];
  2175. }
  2176. if (_shareOC)
  2177. [_shareOC reloadData];
  2178. [self tableViewReload];
  2179. }
  2180. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  2181. {
  2182. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2183. metadataNet.action = actionUnShare;
  2184. metadataNet.fileID = metadata.fileID;
  2185. metadataNet.fileName = metadata.fileName;
  2186. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2187. metadataNet.selector = selectorUnshare;
  2188. metadataNet.serverUrl = serverUrl;
  2189. metadataNet.share = share;
  2190. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2191. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2192. }
  2193. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  2194. {
  2195. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2196. metadataNet.action = actionUpdateShare;
  2197. metadataNet.fileID = metadata.fileID;
  2198. metadataNet.expirationTime = expirationTime;
  2199. metadataNet.password = password;
  2200. metadataNet.selector = selectorUpdateShare;
  2201. metadataNet.serverUrl = serverUrl;
  2202. metadataNet.share = share;
  2203. metadataNet.sharePermission = permission;
  2204. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2205. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2206. }
  2207. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  2208. {
  2209. [_hud hideHud];
  2210. if (_shareOC)
  2211. [_shareOC reloadUserAndGroup:items];
  2212. }
  2213. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2214. {
  2215. [_hud hideHud];
  2216. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2217. }
  2218. - (void)getUserAndGroup:(NSString *)find
  2219. {
  2220. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2221. metadataNet.action = actionGetUserAndGroup;
  2222. metadataNet.options = find;
  2223. metadataNet.selector = selectorGetUserAndGroup;
  2224. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2225. [_hud visibleIndeterminateHud];
  2226. }
  2227. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2228. {
  2229. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2230. metadataNet.action = actionShareWith;
  2231. metadataNet.fileID = metadata.fileID;
  2232. metadataNet.directoryID = directoryID;
  2233. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2234. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2235. metadataNet.serverUrl = serverUrl;
  2236. metadataNet.selector = selectorShare;
  2237. metadataNet.share = user;
  2238. metadataNet.shareeType = shareeType;
  2239. metadataNet.sharePermission = permission;
  2240. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2241. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2242. }
  2243. - (void)openWindowShare:(tableMetadata *)metadata
  2244. {
  2245. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2246. metadataNet.action = actionReadShareServer;
  2247. metadataNet.fileID = metadata.fileID;
  2248. metadataNet.fileName = metadata.fileName;
  2249. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2250. metadataNet.selector = selectorOpenWindowShare;
  2251. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2252. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2253. [_hud visibleIndeterminateHud];
  2254. }
  2255. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2256. {
  2257. CGPoint location = [tapGesture locationInView:self.tableView];
  2258. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2259. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2260. if (metadata)
  2261. [self openWindowShare:metadata];
  2262. }
  2263. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2264. {
  2265. CGPoint location = [tapGesture locationInView:self.tableView];
  2266. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2267. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2268. if (metadata) {
  2269. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2270. vc.metadata = metadata;
  2271. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2272. [self presentViewController:vc animated:YES completion:nil];
  2273. }
  2274. }
  2275. #pragma --------------------------------------------------------------------------------------------
  2276. #pragma mark ===== Favorite =====
  2277. #pragma --------------------------------------------------------------------------------------------
  2278. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2279. {
  2280. _dateReadDataSource = nil;
  2281. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadataNet.fileID favorite:[metadataNet.options boolValue]];
  2282. if (_isSearchMode)
  2283. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  2284. else
  2285. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  2286. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2287. if (metadata.directory && metadata.favorite) {
  2288. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileNameData];
  2289. [[CCSynchronize sharedSynchronize] addFavoriteFolder:dir];
  2290. }
  2291. }
  2292. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2293. {
  2294. }
  2295. - (void)addFavorite:(tableMetadata *)metadata
  2296. {
  2297. if (metadata.directory) {
  2298. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2299. } else {
  2300. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2301. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2302. }
  2303. }
  2304. - (void)removeFavorite:(tableMetadata *)metadata
  2305. {
  2306. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2307. }
  2308. #pragma --------------------------------------------------------------------------------------------
  2309. #pragma mark ===== Local =====
  2310. #pragma --------------------------------------------------------------------------------------------
  2311. - (void)addLocal:(tableMetadata *)metadata
  2312. {
  2313. if (metadata.errorPasscode || !metadata.uuid) return;
  2314. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2315. if ([metadata.type isEqualToString: k_metadataType_file])
  2316. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddLocal selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2317. if ([metadata.type isEqualToString: k_metadataType_template]) {
  2318. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileName]];
  2319. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  2320. }
  2321. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2322. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2323. }
  2324. #pragma --------------------------------------------------------------------------------------------
  2325. #pragma mark ===== Open in... =====
  2326. #pragma --------------------------------------------------------------------------------------------
  2327. - (void)openIn:(tableMetadata *)metadata
  2328. {
  2329. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2330. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2331. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2332. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2333. }
  2334. #pragma --------------------------------------------------------------------------------------------
  2335. #pragma mark ===== Remove Local File =====
  2336. #pragma --------------------------------------------------------------------------------------------
  2337. - (void)removeLocalFile:(tableMetadata *)metadata
  2338. {
  2339. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2340. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  2341. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  2342. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:nil];
  2343. }
  2344. #pragma --------------------------------------------------------------------------------------------
  2345. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2346. #pragma --------------------------------------------------------------------------------------------
  2347. - (void)orderTable:(NSString *)order
  2348. {
  2349. [CCUtility setOrderSettings:order];
  2350. // Clear data-read of DataSource
  2351. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2352. }
  2353. - (void)ascendingTable:(BOOL)ascending
  2354. {
  2355. [CCUtility setAscendingSettings:ascending];
  2356. // Clear data-read of DataSource
  2357. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2358. }
  2359. - (void)directoryOnTop:(BOOL)directoryOnTop
  2360. {
  2361. [CCUtility setDirectoryOnTop:directoryOnTop];
  2362. // Clear data-read of DataSource
  2363. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2364. }
  2365. - (void)tableGroupBy:(NSString *)groupBy
  2366. {
  2367. [CCUtility setGroupBySettings:groupBy];
  2368. // Clear data-read of DataSource
  2369. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2370. }
  2371. #pragma --------------------------------------------------------------------------------------------
  2372. #pragma mark ==== Menu LOGO ====
  2373. #pragma --------------------------------------------------------------------------------------------
  2374. - (void)menuLogo
  2375. {
  2376. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2377. return;
  2378. // Brand
  2379. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2380. return;
  2381. if ([app.netQueue operationCount] > 0 || [app.netQueueDownload operationCount] > 0 || [app.netQueueDownloadWWan operationCount] > 0 || [app.netQueueUpload operationCount] > 0 || [app.netQueueUploadWWan operationCount] > 0 || [[NCManageDatabase sharedInstance] countAutomaticUploadWithSession:nil] > 0) {
  2382. [app messageNotification:@"_transfers_in_queue_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  2383. return;
  2384. }
  2385. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  2386. NSMutableArray *menuArray = [NSMutableArray new];
  2387. for (NSString *account in listAccount) {
  2388. if ([account isEqualToString:app.activeAccount]) continue;
  2389. CCMenuItem *item = [[CCMenuItem alloc] init];
  2390. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2391. item.argument = account;
  2392. item.image = [UIImage imageNamed:@"menuLogoUser"];
  2393. item.target = self;
  2394. item.action = @selector(changeDefaultAccount:);
  2395. [menuArray addObject:item];
  2396. }
  2397. if ([menuArray count] == 0)
  2398. return;
  2399. OptionalConfiguration options;
  2400. Color textColor, backgroundColor;
  2401. textColor.R = 0;
  2402. textColor.G = 0;
  2403. textColor.B = 0;
  2404. backgroundColor.R = 1;
  2405. backgroundColor.G = 1;
  2406. backgroundColor.B = 1;
  2407. NSInteger originY = 60;
  2408. options.arrowSize = 9;
  2409. options.marginXSpacing = 7;
  2410. options.marginYSpacing = 10;
  2411. options.intervalSpacing = 20;
  2412. options.menuCornerRadius = 6.5;
  2413. options.maskToBackground = NO;
  2414. options.shadowOfMenu = YES;
  2415. options.hasSeperatorLine = YES;
  2416. options.seperatorLineHasInsets = YES;
  2417. options.textColor = textColor;
  2418. options.menuBackgroundColor = backgroundColor;
  2419. CGRect rect = self.view.frame;
  2420. rect.origin.y = rect.origin.y + originY;
  2421. rect.size.height = rect.size.height - originY;
  2422. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2423. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2424. }
  2425. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2426. {
  2427. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2428. // STOP, erase all in queue networking
  2429. [app cancelAllOperations];
  2430. [[CCNetworking sharedNetworking] settingSessionsDownload:YES upload:YES taskStatus:k_taskStatusCancel activeAccount:app.activeAccount activeUser:app.activeUser activeUrl:app.activeUrl];
  2431. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2432. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2433. if (tableAccount)
  2434. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activePassword:tableAccount.password];
  2435. // go to home sweet home
  2436. [[NSNotificationCenter defaultCenter] postNotificationName:@"initializeMain" object:nil];
  2437. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2438. });
  2439. }
  2440. #pragma --------------------------------------------------------------------------------------------
  2441. #pragma mark ==== ReMenu ====
  2442. #pragma --------------------------------------------------------------------------------------------
  2443. - (void)createReMenuBackgroundView:(REMenu *)menu
  2444. {
  2445. __block CGFloat navigationBarH = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;
  2446. _reMenuBackgroundView.frame = CGRectMake(0, navigationBarH, self.view.frame.size.width, self.view.frame.size.height);
  2447. [UIView animateWithDuration:0.2 animations:^{
  2448. float height = (self.view.frame.size.height + navigationBarH) - (menu.menuView.frame.size.height - self.navigationController.navigationBar.frame.size.height + 3);
  2449. if (height < self.tabBarController.tabBar.frame.size.height)
  2450. height = self.tabBarController.tabBar.frame.size.height;
  2451. _reMenuBackgroundView.frame = CGRectMake(0, self.view.frame.size.height + navigationBarH, self.view.frame.size.width, - height);
  2452. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2453. }];
  2454. }
  2455. - (void)createReMainMenu
  2456. {
  2457. NSString *ordinamento;
  2458. NSString *groupBy = _directoryGroupBy;
  2459. __block NSString *nuovoOrdinamento;
  2460. NSString *titoloNuovo, *titoloAttuale;
  2461. BOOL ascendente;
  2462. __block BOOL nuovoAscendente;
  2463. UIImage *image;
  2464. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2465. app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"seleziona"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2466. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2467. [self tableViewSelect:YES];
  2468. }
  2469. }];
  2470. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2471. ordinamento = _directoryOrder;
  2472. if ([ordinamento isEqualToString:@"fileName"]) {
  2473. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] color:[NCBrandColor sharedInstance].brand];
  2474. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2475. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2476. nuovoOrdinamento = @"fileDate";
  2477. }
  2478. if ([ordinamento isEqualToString:@"fileDate"]) {
  2479. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] color:[NCBrandColor sharedInstance].brand];
  2480. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2481. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2482. nuovoOrdinamento = @"fileName";
  2483. }
  2484. app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2485. [self orderTable:nuovoOrdinamento];
  2486. }];
  2487. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2488. ascendente = [CCUtility getAscendingSettings];
  2489. if (ascendente) {
  2490. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] color:[NCBrandColor sharedInstance].brand];
  2491. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2492. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2493. nuovoAscendente = false;
  2494. }
  2495. if (!ascendente) {
  2496. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] color:[NCBrandColor sharedInstance].brand];
  2497. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2498. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2499. nuovoAscendente = true;
  2500. }
  2501. app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2502. [self ascendingTable:nuovoAscendente];
  2503. }];
  2504. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2505. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2506. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2507. app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2508. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2509. else [self tableGroupBy:@"alphabetic"];
  2510. }];
  2511. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2512. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2513. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2514. app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByTypeFile"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2515. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2516. else [self tableGroupBy:@"typefile"];
  2517. }];
  2518. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2519. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2520. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2521. app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2522. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2523. else [self tableGroupBy:@"date"];
  2524. }];
  2525. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2526. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2527. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2528. app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"menuDirectoryOnTop"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2529. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2530. else [self directoryOnTop:YES];
  2531. }];
  2532. // REMENU --------------------------------------------------------------------------------------------------------------
  2533. app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2534. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2535. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2536. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2537. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2538. app.reMainMenu.separatorHeight = 0.5;
  2539. app.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2540. app.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2541. app.reMainMenu.textColor = [UIColor blackColor];
  2542. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2543. app.reMainMenu.textShadowColor = nil;
  2544. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2545. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2546. app.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2547. app.reMainMenu.highlightedSeparatorColor = nil;
  2548. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2549. app.reMainMenu.highlightedTextShadowColor = nil;
  2550. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2551. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2552. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2553. app.reMainMenu.subtitleTextShadowColor = nil;
  2554. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2555. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2556. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2557. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2558. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2559. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2560. app.reMainMenu.borderWidth = 0.3;
  2561. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2562. app.reMainMenu.animationDuration = 0.2;
  2563. app.reMainMenu.closeAnimationDuration = 0.2;
  2564. app.reMainMenu.bounce = NO;
  2565. [app.reMainMenu setClosePreparationBlock:^{
  2566. // Backgroun reMenu (Gesture)
  2567. [_reMenuBackgroundView removeFromSuperview];
  2568. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2569. }];
  2570. }
  2571. - (void)toggleReMainMenu
  2572. {
  2573. if (app.reMainMenu.isOpen) {
  2574. [app.reMainMenu close];
  2575. } else {
  2576. [self createReMainMenu];
  2577. [app.reMainMenu showFromNavigationController:self.navigationController];
  2578. // Backgroun reMenu & (Gesture)
  2579. [self createReMenuBackgroundView:app.reMainMenu];
  2580. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2581. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2582. }
  2583. }
  2584. - (void)createReSelectMenu
  2585. {
  2586. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2587. app.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"deleteSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2588. [self deleteSelectionFile];
  2589. }];
  2590. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2591. app.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"moveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2592. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2593. }];
  2594. if (app.isCryptoCloudMode) {
  2595. // ITEM ENCRYPTED ------------------------------------------------------------------------------------------------------
  2596. app.encryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"encryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2597. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2598. }];
  2599. // ITEM DECRYPTED ----------------------------------------------------------------------------------------------------
  2600. app.decryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"decryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2601. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2602. }];
  2603. }
  2604. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2605. app.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"downloadSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2606. [self downloadSelectedFiles];
  2607. }];
  2608. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2609. app.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"saveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2610. [self saveSelectedFiles];
  2611. }];
  2612. // REMENU --------------------------------------------------------------------------------------------------------------
  2613. if (app.isCryptoCloudMode) {
  2614. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2615. } else {
  2616. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2617. }
  2618. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2619. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2620. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2621. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2622. app.reSelectMenu.separatorHeight = 0.5;
  2623. app.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2624. app.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2625. app.reSelectMenu.textColor = [UIColor blackColor];
  2626. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2627. app.reSelectMenu.textShadowColor = nil;
  2628. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2629. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2630. app.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2631. app.reSelectMenu.highlightedSeparatorColor = nil;
  2632. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2633. app.reSelectMenu.highlightedTextShadowColor = nil;
  2634. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2635. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2636. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2637. app.reSelectMenu.subtitleTextShadowColor = nil;
  2638. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2639. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2640. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2641. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2642. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2643. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2644. app.reSelectMenu.borderWidth = 0.3;
  2645. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2646. app.reSelectMenu.closeAnimationDuration = 0.2;
  2647. app.reSelectMenu.animationDuration = 0.2;
  2648. app.reSelectMenu.bounce = NO;
  2649. [app.reSelectMenu setClosePreparationBlock:^{
  2650. // Backgroun reMenu (Gesture)
  2651. [_reMenuBackgroundView removeFromSuperview];
  2652. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2653. }];
  2654. }
  2655. - (void)toggleReSelectMenu
  2656. {
  2657. if (app.reSelectMenu.isOpen) {
  2658. [app.reSelectMenu close];
  2659. } else {
  2660. [self createReSelectMenu];
  2661. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2662. // Backgroun reMenu & (Gesture)
  2663. [self createReMenuBackgroundView:app.reSelectMenu];
  2664. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2665. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2666. }
  2667. }
  2668. #pragma --------------------------------------------------------------------------------------------
  2669. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2670. #pragma --------------------------------------------------------------------------------------------
  2671. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2672. {
  2673. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2674. UITableView *tableView = (UITableView*)self.view;
  2675. CGPoint touchPoint = [recognizer locationInView:self.view];
  2676. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2677. if (indexPath)
  2678. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2679. else
  2680. _metadata = nil;
  2681. [self becomeFirstResponder];
  2682. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2683. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2684. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2685. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2686. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2687. UIMenuItem *pasteFileEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_encrypted_", nil) action:@selector(pasteFileEncrypted:)];
  2688. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2689. UIMenuItem *pasteFilesEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_encrypted_", nil) action:@selector(pasteFilesEncrypted:)];
  2690. if (app.isCryptoCloudMode)
  2691. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, pasteFileEncryptedItem, pasteFilesEncryptedItem, nil]];
  2692. else
  2693. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2694. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2695. [menuController setMenuVisible:YES animated:YES];
  2696. }
  2697. }
  2698. - (BOOL)canBecomeFirstResponder
  2699. {
  2700. return YES;
  2701. }
  2702. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2703. {
  2704. // For copy file, copy files, Open in ... :
  2705. //
  2706. // NO Directory
  2707. // NO Error Passcode
  2708. // NO In Session mode (download/upload)
  2709. // NO Template
  2710. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2711. if (_isSelectedMode == NO && _metadata && !_metadata.directory && !_metadata.errorPasscode && [_metadata.session length] == 0 && ![_metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2712. // NO Cryptated with Title lenght = 0
  2713. if (!_metadata.cryptated || (_metadata.cryptated && _metadata.title.length > 0))
  2714. return YES;
  2715. }
  2716. return NO;
  2717. }
  2718. if (@selector(copyFiles:) == action) {
  2719. if (_isSelectedMode) {
  2720. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2721. for (tableMetadata *metadata in selectedMetadatas) {
  2722. if (!metadata.directory && !metadata.errorPasscode && metadata.session.length == 0 && ![metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2723. // NO Cryptated with Title lenght = 0
  2724. if (!metadata.cryptated || (metadata.cryptated && metadata.title.length > 0))
  2725. return YES;
  2726. }
  2727. }
  2728. }
  2729. return NO;
  2730. }
  2731. if (@selector(pasteFile:) == action || @selector(pasteFileEncrypted:) == action) {
  2732. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2733. NSArray *items = [pasteboard items];
  2734. if ([items count] == 1) {
  2735. // Value : (NSData) fileID
  2736. NSDictionary *dic = [items objectAtIndex:0];
  2737. NSData *dataEtag = [dic objectForKey: k_metadataKeyedUnarchiver];
  2738. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataEtag];
  2739. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2740. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2741. if (directoryUser) {
  2742. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2743. return YES;
  2744. }
  2745. return NO;
  2746. } else return NO;
  2747. }
  2748. if (@selector(pasteFiles:) == action || @selector(pasteFilesEncrypted:) == action) {
  2749. BOOL isValid = NO;
  2750. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2751. NSArray *items = [pasteboard items];
  2752. if ([items count] <= 1) return NO;
  2753. for (NSDictionary *dic in items) {
  2754. // Value : (NSData) fileID
  2755. NSData *dataEtag = [dic objectForKey: k_metadataKeyedUnarchiver];
  2756. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataEtag];
  2757. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2758. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2759. if (directoryUser) {
  2760. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2761. isValid = YES;
  2762. }
  2763. }
  2764. return isValid;
  2765. }
  2766. return NO;
  2767. }
  2768. /************************************ COPY ************************************/
  2769. - (void)copyFile:(id)sender
  2770. {
  2771. // Remove all item
  2772. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2773. pasteboard.items = [[NSArray alloc] init];
  2774. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2775. [self copyFileToPasteboard:_metadata];
  2776. } else {
  2777. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2778. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2779. }
  2780. }
  2781. - (void)copyFiles:(id)sender
  2782. {
  2783. // Remove all item
  2784. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2785. pasteboard.items = [[NSArray alloc] init];
  2786. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2787. for (tableMetadata *metadata in selectedMetadatas) {
  2788. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2789. [self copyFileToPasteboard:metadata];
  2790. } else {
  2791. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2792. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2793. }
  2794. }
  2795. [self tableViewSelect:NO];
  2796. }
  2797. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2798. {
  2799. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2800. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2801. // Value : (NSData) fileID
  2802. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2803. [items addObject:item];
  2804. [pasteboard setItems:items];
  2805. }
  2806. /************************************ OPEN IN ... ************************************/
  2807. - (void)openinFile:(id)sender
  2808. {
  2809. [self openIn:_metadata];
  2810. }
  2811. /************************************ PASTE ************************************/
  2812. - (void)pasteFile:(id)sender
  2813. {
  2814. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2815. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2816. }
  2817. - (void)pasteFileEncrypted:(id)sender
  2818. {
  2819. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2820. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2821. }
  2822. - (void)pasteFiles:(id)sender
  2823. {
  2824. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2825. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2826. }
  2827. - (void)pasteFilesEncrypted:(id)sender
  2828. {
  2829. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2830. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2831. }
  2832. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2833. {
  2834. for (NSDictionary *dic in items) {
  2835. // Value : (NSData) fileID
  2836. NSData *dataEtag = [dic objectForKey: k_metadataKeyedUnarchiver];
  2837. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataEtag];
  2838. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2839. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2840. if (!metadata || !account) return;
  2841. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2842. if (directoryUser) {
  2843. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2844. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint]];
  2845. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:_serverUrl cryptated:cryptated onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  2846. }
  2847. }
  2848. }
  2849. }
  2850. #pragma --------------------------------------------------------------------------------------------
  2851. #pragma mark ===== Lock Passcode =====
  2852. #pragma --------------------------------------------------------------------------------------------
  2853. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2854. {
  2855. return _failedAttempts;
  2856. }
  2857. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2858. {
  2859. return _lockUntilDate;
  2860. }
  2861. - (void)passcodeViewCloseButtonPressed:(id)sender
  2862. {
  2863. [self dismissViewControllerAnimated:YES completion:nil];
  2864. }
  2865. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2866. {
  2867. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2868. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2869. _lockUntilDate = nil;
  2870. _failedAttempts = 0;
  2871. aResultHandler(YES);
  2872. } else aResultHandler(NO);
  2873. } else aResultHandler(YES);
  2874. }
  2875. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2876. {
  2877. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2878. switch (aViewController.type) {
  2879. case BKPasscodeViewControllerCheckPasscodeType: {
  2880. if (aViewController.fromType == CCBKPasscodeFromPasscode) {
  2881. // verifichiamo se il passcode è corretto per il seguente file -> UUID
  2882. if ([[CCCrypto sharedManager] verifyPasscode:aPasscode uuid:_metadata.uuid text:_metadata.title]) {
  2883. // scriviamo il passcode
  2884. [CCUtility setKeyChainPasscodeForUUID:_metadata.uuid conPasscode:aPasscode];
  2885. [self readFolderWithForced:YES serverUrl:_serverUrl];
  2886. } else {
  2887. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2888. [alertView show];
  2889. }
  2890. }
  2891. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2892. // possiamo procedere alla prossima directory
  2893. [self performSegueDirectoryWithControlPasscode:false];
  2894. // avviamo la sessione Passcode Lock con now
  2895. app.sessionePasscodeLock = [NSDate date];
  2896. }
  2897. // disattivazione lock cartella
  2898. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2899. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2900. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2901. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO]) {
  2902. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2903. }
  2904. [self.tableView reloadData];
  2905. }
  2906. }
  2907. break;
  2908. default:
  2909. break;
  2910. }
  2911. }
  2912. - (void)comandoLockPassword
  2913. {
  2914. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2915. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2916. // se non è abilitato il Lock Passcode esci
  2917. if ([[CCUtility getBlockCode] length] == 0) {
  2918. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2919. [alertView show];
  2920. return;
  2921. }
  2922. // se è richiesta la disattivazione si chiede la password
  2923. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  2924. if (directory.lock) {
  2925. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2926. viewController.delegate = self;
  2927. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2928. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2929. viewController.inputViewTitlePassword = YES;
  2930. if ([CCUtility getSimplyBlockCode]) {
  2931. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2932. viewController.passcodeInputView.maximumLength = 6;
  2933. } else {
  2934. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2935. viewController.passcodeInputView.maximumLength = 64;
  2936. }
  2937. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2938. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2939. viewController.touchIDManager = touchIDManager;
  2940. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2941. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2942. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  2943. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2944. [self presentViewController:navigationController animated:YES completion:nil];
  2945. return;
  2946. }
  2947. // ---------------- ACTIVATE PASSWORD
  2948. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES]) {
  2949. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2950. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2951. } else {
  2952. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2953. }
  2954. }
  2955. #pragma mark -
  2956. #pragma --------------------------------------------------------------------------------------------
  2957. #pragma mark ===== Swipe Tablet -> menu =====
  2958. #pragma --------------------------------------------------------------------------------------------
  2959. // more
  2960. - (NSString *)tableView:(UITableView *)tableView titleForSwipeAccessoryButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
  2961. return NSLocalizedString(@"_more_", nil);
  2962. }
  2963. - (void)tableView:(UITableView *)tableView swipeAccessoryButtonPushedForRowAtIndexPath:(NSIndexPath *)indexPath
  2964. {
  2965. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2966. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2967. NSString *titoloCriptaDecripta, *titoloLock, *titleFavorite;
  2968. if (_metadata.cryptated) titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_decrypt_", nil)];
  2969. else titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_", nil)];
  2970. if (_metadata.favorite) {
  2971. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  2972. } else {
  2973. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  2974. }
  2975. if (_metadata.directory) {
  2976. // calcolo lockServerUrl
  2977. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2978. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  2979. if (directory.lock)
  2980. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2981. else
  2982. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2983. }
  2984. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", _metadata.fileID]];
  2985. /******************************************* AHKActionSheet *******************************************/
  2986. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.view title:nil];
  2987. actionSheet.animationDuration = 0.2;
  2988. actionSheet.blurRadius = 0.0f;
  2989. actionSheet.blurTintColor = [UIColor colorWithWhite:0.0f alpha:0.50f];
  2990. actionSheet.buttonHeight = 50.0;
  2991. actionSheet.cancelButtonHeight = 50.0f;
  2992. actionSheet.separatorHeight = 5.0f;
  2993. actionSheet.automaticallyTintButtonImages = @(NO);
  2994. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].cryptocloud };
  2995. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2996. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].brand };
  2997. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2998. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  2999. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  3000. /******************************************* DIRECTORY *******************************************/
  3001. if (_metadata.directory) {
  3002. BOOL lockDirectory = NO;
  3003. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3004. // Directory bloccata ?
  3005. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", dirServerUrl]];
  3006. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3007. NSString *cameraUploadFolderName = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderName];
  3008. NSString *cameraUploadFolderPath = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderPathWithActiveUrl:app.activeUrl];
  3009. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3010. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:_metadata.iconName] color:[NCBrandColor sharedInstance].brand]
  3011. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3012. height: 50.0
  3013. type: AHKActionSheetButtonTypeDisabled
  3014. handler: nil
  3015. ];
  3016. if (!lockDirectory && !_metadata.cryptated) {
  3017. [actionSheet addButtonWithTitle:titleFavorite
  3018. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetFavorite"] color:[NCBrandColor sharedInstance].brand]
  3019. backgroundColor:[UIColor whiteColor]
  3020. height: 50.0
  3021. type:AHKActionSheetButtonTypeDefault
  3022. handler:^(AHKActionSheet *as) {
  3023. // close swipe
  3024. [self setEditing:NO animated:YES];
  3025. if (_metadata.favorite)
  3026. [self removeFavorite:_metadata];
  3027. else
  3028. [self addFavorite:_metadata];
  3029. }];
  3030. }
  3031. if (_metadata.cryptated == NO && !lockDirectory) {
  3032. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3033. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3034. backgroundColor:[UIColor whiteColor]
  3035. height: 50.0
  3036. type:AHKActionSheetButtonTypeDefault
  3037. handler:^(AHKActionSheet *as) {
  3038. // close swipe
  3039. [self setEditing:NO animated:YES];
  3040. [self openWindowShare:_metadata];
  3041. }];
  3042. }
  3043. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory) {
  3044. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3045. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3046. backgroundColor:[UIColor whiteColor]
  3047. height: 50.0
  3048. type:AHKActionSheetButtonTypeDefault
  3049. handler:^(AHKActionSheet *as) {
  3050. // close swipe
  3051. [self setEditing:NO animated:YES];
  3052. //chiediamo il nome del file
  3053. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3054. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3055. alertView.tag = alertRename;
  3056. UITextField *textField = [alertView textFieldAtIndex:0];
  3057. textField.text = _metadata.fileNamePrint;
  3058. [alertView show];
  3059. }];
  3060. }
  3061. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory) {
  3062. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3063. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3064. backgroundColor:[UIColor whiteColor]
  3065. height: 50.0
  3066. type:AHKActionSheetButtonTypeDefault
  3067. handler:^(AHKActionSheet *as) {
  3068. // close swipe
  3069. [self setEditing:NO animated:YES];
  3070. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3071. }];
  3072. }
  3073. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && _metadata.cryptated == NO) {
  3074. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  3075. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brand]
  3076. backgroundColor:[UIColor whiteColor]
  3077. height: 50.0
  3078. type:AHKActionSheetButtonTypeDefault
  3079. handler:^(AHKActionSheet *as) {
  3080. // close swipe
  3081. [self setEditing:NO animated:YES];
  3082. // Settings new folder Automatatic upload
  3083. NSString *oldPath = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderPathWithActiveUrl:app.activeUrl];
  3084. [[NCManageDatabase sharedInstance] setAccountCameraUploadFolderName:_metadata.fileName];
  3085. [[NCManageDatabase sharedInstance] setAccountCameraUploadFolderPath:serverUrl activeUrl:app.activeUrl];
  3086. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:oldPath directoryID:nil];
  3087. if (app.activeAccount.length > 0 && app.activePhotosCameraUpload)
  3088. [app.activePhotosCameraUpload reloadDatasourceForced];
  3089. [self readFolderWithForced:YES serverUrl:serverUrl];
  3090. NSLog(@"[LOG] Update Folder Photo");
  3091. NSString *folderCameraUpload = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderPathWithActiveUrl:app.activeUrl];
  3092. if ([folderCameraUpload length] > 0)
  3093. [[CCSynchronize sharedSynchronize] readFolderServerUrl:folderCameraUpload directoryID:[[NCManageDatabase sharedInstance] getDirectoryID:folderCameraUpload] selector:selectorReadFolder];
  3094. }];
  3095. }
  3096. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES)) {
  3097. [actionSheet addButtonWithTitle:titoloLock
  3098. image:[UIImage imageNamed:@"actionSheetLock"]
  3099. backgroundColor:[UIColor whiteColor]
  3100. height: 50.0
  3101. type:AHKActionSheetButtonTypeEncrypted
  3102. handler:^(AHKActionSheet *as) {
  3103. // close swipe
  3104. [self setEditing:NO animated:YES];
  3105. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  3106. }];
  3107. }
  3108. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory && app.isCryptoCloudMode) {
  3109. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3110. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3111. backgroundColor:[UIColor whiteColor]
  3112. height: 50.0
  3113. type:AHKActionSheetButtonTypeEncrypted
  3114. handler:^(AHKActionSheet *as) {
  3115. // close swipe
  3116. [self setEditing:NO animated:YES];
  3117. [self performSelector:@selector(encyptedDecryptedFolder) withObject:nil];
  3118. }];
  3119. }
  3120. [actionSheet show];
  3121. }
  3122. /******************************************* FILE *******************************************/
  3123. if ([_metadata.type isEqualToString: k_metadataType_file] && !_metadata.directory) {
  3124. UIImage *iconHeader;
  3125. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3126. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  3127. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  3128. else
  3129. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3130. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3131. image: iconHeader
  3132. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3133. height: 50.0
  3134. type: AHKActionSheetButtonTypeDisabled
  3135. handler: nil
  3136. ];
  3137. if (!_metadata.cryptated) {
  3138. [actionSheet addButtonWithTitle:titleFavorite
  3139. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetFavorite"] color:[NCBrandColor sharedInstance].brand]
  3140. backgroundColor:[UIColor whiteColor]
  3141. height: 50.0
  3142. type:AHKActionSheetButtonTypeDefault
  3143. handler:^(AHKActionSheet *as) {
  3144. // close swipe
  3145. [self setEditing:NO animated:YES];
  3146. if (_metadata.favorite)
  3147. [self removeFavorite:_metadata];
  3148. else
  3149. [self addFavorite:_metadata];
  3150. }];
  3151. }
  3152. if (_metadata.cryptated == NO) {
  3153. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3154. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3155. backgroundColor:[UIColor whiteColor]
  3156. height: 50.0
  3157. type:AHKActionSheetButtonTypeDefault
  3158. handler:^(AHKActionSheet *as) {
  3159. // close swipe
  3160. [self setEditing:NO animated:YES];
  3161. [self openWindowShare:_metadata];
  3162. }];
  3163. }
  3164. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  3165. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetOpenIn"] color:[NCBrandColor sharedInstance].brand]
  3166. backgroundColor:[UIColor whiteColor]
  3167. height: 50.0
  3168. type:AHKActionSheetButtonTypeDefault
  3169. handler:^(AHKActionSheet *as) {
  3170. // close swipe
  3171. [self setEditing:NO animated:YES];
  3172. [self performSelector:@selector(openIn:) withObject:_metadata];
  3173. }];
  3174. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3175. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3176. backgroundColor:[UIColor whiteColor]
  3177. height: 50.0
  3178. type:AHKActionSheetButtonTypeDefault
  3179. handler:^(AHKActionSheet *as) {
  3180. // close swipe
  3181. [self setEditing:NO animated:YES];
  3182. //chiediamo il nome del file
  3183. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3184. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3185. alertView.tag = alertRename;
  3186. UITextField *textField = [alertView textFieldAtIndex:0];
  3187. textField.text = _metadata.fileNamePrint;
  3188. [alertView show];
  3189. }];
  3190. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3191. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3192. backgroundColor:[UIColor whiteColor]
  3193. height: 50.0
  3194. type:AHKActionSheetButtonTypeDefault
  3195. handler:^(AHKActionSheet *as) {
  3196. // close swipe
  3197. [self setEditing:NO animated:YES];
  3198. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3199. }];
  3200. if (localFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3201. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3202. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRemoveLocal"] color:[NCBrandColor sharedInstance].brand]
  3203. backgroundColor:[UIColor whiteColor]
  3204. height: 50.0
  3205. type:AHKActionSheetButtonTypeDefault
  3206. handler:^(AHKActionSheet *as) {
  3207. // close swipe
  3208. [self setEditing:NO animated:YES];
  3209. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3210. }];
  3211. }
  3212. if (app.isCryptoCloudMode) {
  3213. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3214. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3215. backgroundColor:[UIColor whiteColor]
  3216. height: 50.0
  3217. type:AHKActionSheetButtonTypeEncrypted
  3218. handler:^(AHKActionSheet *as) {
  3219. // close swipe
  3220. [self setEditing:NO animated:YES];
  3221. [self performSelector:@selector(cmdEncryptedDecryptedFile) withObject:nil];
  3222. }];
  3223. }
  3224. [actionSheet show];
  3225. }
  3226. /******************************************* TEMPLATE *******************************************/
  3227. if ([_metadata.type isEqualToString: k_metadataType_template]) {
  3228. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3229. image: [UIImage imageNamed:_metadata.iconName]
  3230. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3231. height: 50.0
  3232. type: AHKActionSheetButtonTypeDisabled
  3233. handler: nil
  3234. ];
  3235. if ([_metadata.model isEqualToString:@"note"]) {
  3236. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3237. image:[UIImage imageNamed:@"actionSheetRename"]
  3238. backgroundColor:[UIColor whiteColor]
  3239. height: 50.0
  3240. type:AHKActionSheetButtonTypeDefault
  3241. handler:^(AHKActionSheet *as) {
  3242. // close swipe
  3243. [self setEditing:NO animated:YES];
  3244. //chiediamo il nome del file
  3245. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3246. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3247. alertView.tag = alertRename;
  3248. UITextField *textField = [alertView textFieldAtIndex:0];
  3249. textField.text = _metadata.fileNamePrint;
  3250. [alertView show];
  3251. }];
  3252. }
  3253. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3254. image:[UIImage imageNamed:@"actionSheetMove"]
  3255. backgroundColor:[UIColor whiteColor]
  3256. height: 50.0
  3257. type:AHKActionSheetButtonTypeDefault
  3258. handler:^(AHKActionSheet *as) {
  3259. // close swipe
  3260. [self setEditing:NO animated:YES];
  3261. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3262. }];
  3263. [actionSheet show];
  3264. }
  3265. }
  3266. - (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
  3267. {
  3268. return NSLocalizedString(@"_delete_", nil);
  3269. }
  3270. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3271. {
  3272. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3273. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3274. return NO;
  3275. if (metadata == nil || metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0) return NO;
  3276. else return YES;
  3277. }
  3278. - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
  3279. {
  3280. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3281. if (_metadata.errorPasscode || (_metadata.cryptated && [_metadata.title length] == 0) || _metadata.sessionTaskIdentifier >= 0 || _metadata.sessionTaskIdentifier >= 0) return UITableViewCellEditingStyleNone;
  3282. else return UITableViewCellEditingStyleDelete;
  3283. }
  3284. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  3285. {
  3286. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3287. BOOL lockDirectory = NO;
  3288. // Directory locked ?
  3289. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID] addFileName:_metadata.fileNameData];
  3290. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  3291. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil)
  3292. lockDirectory = YES;
  3293. if (lockDirectory && editingStyle == UITableViewCellEditingStyleDelete) {
  3294. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  3295. return;
  3296. }
  3297. if (editingStyle == UITableViewCellEditingStyleDelete) {
  3298. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  3299. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  3300. style:UIAlertActionStyleDestructive
  3301. handler:^(UIAlertAction *action) {
  3302. [self performSelector:@selector(deleteFile) withObject:nil];
  3303. }]];
  3304. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  3305. style:UIAlertActionStyleCancel
  3306. handler:^(UIAlertAction *action) {
  3307. [alertController dismissViewControllerAnimated:YES completion:nil];
  3308. }]];
  3309. alertController.popoverPresentationController.sourceView = self.view;
  3310. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  3311. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3312. [alertController.view layoutIfNeeded];
  3313. [self presentViewController:alertController animated:YES completion:nil];
  3314. }
  3315. }
  3316. #pragma --------------------------------------------------------------------------------------------
  3317. #pragma mark - ==== Datasource ====
  3318. #pragma --------------------------------------------------------------------------------------------
  3319. - (void)clearDateReadDataSource:(NSNotification *)notification
  3320. {
  3321. _dateReadDataSource = Nil;
  3322. [self reloadDatasource];
  3323. }
  3324. - (void)reloadDatasource
  3325. {
  3326. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  3327. }
  3328. - (void)reloadDatasource:(NSString *)serverUrl fileID:(NSString *)fileID selector:(NSString *)selector
  3329. {
  3330. // test
  3331. if (app.activeAccount.length == 0 || serverUrl.length == 0)
  3332. return;
  3333. // Search Mode
  3334. if(_isSearchMode) {
  3335. if ([selector length] == 0 || [selector isEqualToString:selectorSearch]) {
  3336. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3337. } else {
  3338. [self readFolderWithForced:NO serverUrl:serverUrl];
  3339. }
  3340. [self tableViewReload];
  3341. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3342. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3343. _noFilesSearchDescription = @"";
  3344. }
  3345. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3346. _noFilesSearchTitle = @"";
  3347. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3348. }
  3349. [self.tableView reloadEmptyDataSet];
  3350. return;
  3351. }
  3352. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3353. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3354. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  3355. [app.activeTransfers reloadDatasource];
  3356. } else {
  3357. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3358. if (main) {
  3359. [main reloadDatasource];
  3360. } else {
  3361. [self tableViewReload];
  3362. [app.activeTransfers reloadDatasource];
  3363. }
  3364. }
  3365. return;
  3366. }
  3367. [app.activeTransfers reloadDatasource];
  3368. // Settaggio variabili per le ottimizzazioni
  3369. _directoryGroupBy = [CCUtility getGroupBySettings];
  3370. _directoryOrder = [CCUtility getOrderSettings];
  3371. // Controllo data lettura Data Source
  3372. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl == %@", serverUrl]];
  3373. NSDate *dateDateRecordDirectory = directory.dateReadDirectory;
  3374. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3375. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3376. _dateReadDataSource = [NSDate date];
  3377. // Data Source
  3378. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@", app.activeAccount, [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl]] sorted:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings]];
  3379. _sectionDataSource = [CCSectionDataSourceMetadata new];
  3380. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3381. } else {
  3382. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3383. }
  3384. [self tableViewReload];
  3385. }
  3386. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3387. {
  3388. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3389. if (selectedRows.count > 0) {
  3390. for (NSIndexPath *selectionIndex in selectedRows) {
  3391. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3392. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3393. [metadatas addObject:metadata];
  3394. }
  3395. }
  3396. return metadatas;
  3397. }
  3398. - (tableMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3399. {
  3400. NSInteger section = indexPath.section + 1;
  3401. NSInteger row = indexPath.row + 1;
  3402. NSInteger totSections =[_sectionDataSource.sections count] ;
  3403. if ((totSections < section) || (section > totSections)) {
  3404. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3405. return nil;
  3406. }
  3407. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3408. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3409. if (fileIDs) {
  3410. NSInteger totRows =[fileIDs count] ;
  3411. if ((totRows < row) || (row > totRows)) {
  3412. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3413. return nil;
  3414. }
  3415. } else {
  3416. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3417. return nil;
  3418. }
  3419. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3420. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3421. return metadata;
  3422. }
  3423. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3424. {
  3425. NSInteger totSections =[_sectionDataSource.sections count] ;
  3426. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3427. #if DEBUG
  3428. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:[NSString stringWithFormat:@"DEBUG [3] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section] delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3429. [alertView show];
  3430. #endif
  3431. return nil;
  3432. }
  3433. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3434. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3435. }
  3436. #pragma --------------------------------------------------------------------------------------------
  3437. #pragma mark - ==== Table ====
  3438. #pragma --------------------------------------------------------------------------------------------
  3439. - (void)tableViewSelect:(BOOL)edit
  3440. {
  3441. // chiudiamo eventuali swipe aperti
  3442. if (edit) [self.tableView setEditing:NO animated:NO];
  3443. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3444. [self.tableView setEditing:edit animated:YES];
  3445. _isSelectedMode = edit;
  3446. if (edit)
  3447. [self setUINavigationBarSelected];
  3448. else
  3449. [self setUINavigationBarDefault];
  3450. [self setTitle];
  3451. }
  3452. - (void)tableViewReload
  3453. {
  3454. // ricordiamoci le row selezionate
  3455. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3456. [self.tableView reloadData];
  3457. for (NSIndexPath *path in indexPaths)
  3458. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3459. [self setTableViewFooter];
  3460. if (self.tableView.editing)
  3461. [self setTitle];
  3462. }
  3463. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3464. {
  3465. return 60;
  3466. }
  3467. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3468. {
  3469. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3470. }
  3471. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3472. {
  3473. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3474. }
  3475. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3476. {
  3477. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3478. NSString *sectionTitle = [sections objectAtIndex:section];
  3479. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3480. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3481. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3482. return 20.f;
  3483. }
  3484. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3485. {
  3486. float shift;
  3487. UIVisualEffectView *visualEffectView;
  3488. // Titolo
  3489. NSString *titleSection;
  3490. // Controllo
  3491. if ([_sectionDataSource.sections count] == 0)
  3492. return nil;
  3493. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]]) titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3494. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]]) titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3495. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3496. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3497. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3498. else titleSection = NSLocalizedString(titleSection,nil);
  3499. // Formato titolo
  3500. NSString *currentDevice = [CCUtility currentDevice];
  3501. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3502. visualEffectView = [[UIVisualEffectView alloc] init];
  3503. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3504. } else {
  3505. UIVisualEffect *blurEffect;
  3506. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3507. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3508. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3509. }
  3510. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3511. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) shift = - 35;
  3512. else shift = - 20;
  3513. } else shift = - 10;
  3514. // Title
  3515. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3516. titleLabel.backgroundColor = [UIColor clearColor];
  3517. titleLabel.textColor = [UIColor blackColor];
  3518. titleLabel.font = [UIFont systemFontOfSize:12];
  3519. titleLabel.textAlignment = NSTextAlignmentLeft;
  3520. titleLabel.text = titleSection;
  3521. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3522. [visualEffectView addSubview:titleLabel];
  3523. // Elements
  3524. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3525. elementLabel.backgroundColor = [UIColor clearColor];
  3526. elementLabel.textColor = [UIColor blackColor];;
  3527. elementLabel.font = [UIFont systemFontOfSize:12];
  3528. elementLabel.textAlignment = NSTextAlignmentRight;
  3529. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3530. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3531. NSUInteger rowsCount = [metadatas count];
  3532. if (rowsCount == 0) return nil;
  3533. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3534. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3535. [visualEffectView addSubview:elementLabel];
  3536. return visualEffectView;
  3537. }
  3538. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3539. {
  3540. return [_sectionDataSource.sections indexOfObject:title];
  3541. }
  3542. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3543. {
  3544. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3545. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3546. else
  3547. return nil;
  3548. }
  3549. /*
  3550. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3551. {
  3552. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3553. }
  3554. }
  3555. */
  3556. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3557. {
  3558. NSString *typeCell;
  3559. NSString *dataFile;
  3560. NSString *lunghezzaFile;
  3561. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3562. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata]) {
  3563. return [tableView dequeueReusableCellWithIdentifier:@"CellMainTransfer"];
  3564. }
  3565. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3566. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3567. else typeCell = @"CellMainTransfer";
  3568. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3569. // separator
  3570. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3571. // change color selection
  3572. UIView *selectionColor = [[UIView alloc] init];
  3573. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3574. cell.selectedBackgroundView = selectionColor;
  3575. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3576. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3577. // ----------------------------------------------------------------------------------------------------------
  3578. // DEFAULT
  3579. // ----------------------------------------------------------------------------------------------------------
  3580. cell.fileImageView.image = nil;
  3581. cell.statusImageView.image = nil;
  3582. cell.offlineImageView.image = nil;
  3583. cell.synchronizedImageView.image = nil;
  3584. cell.sharedImageView.image = nil;
  3585. cell.labelTitle.enabled = YES;
  3586. cell.labelTitle.text = @"";
  3587. cell.labelInfoFile.enabled = YES;
  3588. cell.labelInfoFile.text = @"";
  3589. cell.progressView.progress = 0.0;
  3590. cell.progressView.hidden = YES;
  3591. cell.cancelTaskButton.hidden = YES;
  3592. cell.reloadTaskButton.hidden = YES;
  3593. cell.stopTaskButton.hidden = YES;
  3594. // Encrypted color
  3595. if (metadata.cryptated) {
  3596. cell.labelTitle.textColor = [NCBrandColor sharedInstance].cryptocloud;
  3597. } else {
  3598. cell.labelTitle.textColor = [UIColor blackColor];
  3599. }
  3600. // ----------------------------------------------------------------------------------------------------------
  3601. // File Name & Folder
  3602. // ----------------------------------------------------------------------------------------------------------
  3603. // nome del file
  3604. cell.labelTitle.text = metadata.fileNamePrint;
  3605. // è una directory
  3606. if (metadata.directory) {
  3607. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3608. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3609. lunghezzaFile = @" ";
  3610. // ----------------------------------------------------------------------------------------------------------
  3611. // Favorite Folder
  3612. // ----------------------------------------------------------------------------------------------------------
  3613. if (metadata.favorite) {
  3614. cell.offlineImageView.image = [UIImage imageNamed:@"favorite"];
  3615. }
  3616. } else {
  3617. // File
  3618. dataFile = [CCUtility dateDiff:metadata.date];
  3619. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3620. // Plist ancora da scaricare
  3621. if (metadata.cryptated && [metadata.title length] == 0) {
  3622. dataFile = @" ";
  3623. lunghezzaFile = @" ";
  3624. }
  3625. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  3626. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3627. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3628. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3629. if ([metadata.type isEqualToString: k_metadataType_template] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO)
  3630. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", dataFile];
  3631. if ([metadata.type isEqualToString: k_metadataType_file] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO) {
  3632. if (localFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3633. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ • %@", dataFile, lunghezzaFile];
  3634. else
  3635. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ ◦ %@", dataFile, lunghezzaFile];
  3636. }
  3637. // Plist ancora da scaricare
  3638. if ([dataFile isEqualToString:@" "] && [lunghezzaFile isEqualToString:@" "])
  3639. cell.labelInfoFile.text = NSLocalizedString(@"_no_plist_pull_down_",nil);
  3640. cell.accessoryType = UITableViewCellAccessoryNone;
  3641. }
  3642. // ----------------------------------------------------------------------------------------------------------
  3643. // File Image View
  3644. // ----------------------------------------------------------------------------------------------------------
  3645. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3646. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3647. cell.fileImageView.image = [app.icoImagesCache objectForKey:metadata.fileID];
  3648. if (cell.fileImageView.image == nil) {
  3649. NSString *fileID = metadata.fileID;
  3650. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  3651. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID]];
  3652. [app.icoImagesCache setObject:image forKey:fileID];
  3653. dispatch_async(dispatch_get_main_queue(), ^{
  3654. CCCellMainTransfer *cell = [tableView cellForRowAtIndexPath:indexPath];
  3655. if (cell)
  3656. cell.fileImageView.image = image;
  3657. });
  3658. });
  3659. }
  3660. } else {
  3661. if (metadata.directory)
  3662. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:metadata.iconName] color:[NCBrandColor sharedInstance].brand];
  3663. else
  3664. cell.fileImageView.image = [UIImage imageNamed:metadata.iconName];
  3665. if (metadata.thumbnailExists)
  3666. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3667. }
  3668. // ----------------------------------------------------------------------------------------------------------
  3669. // Image Status cyptated & Lock Passcode
  3670. // ----------------------------------------------------------------------------------------------------------
  3671. // File Cyptated
  3672. if (metadata.cryptated && metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_template] == NO) {
  3673. cell.statusImageView.image = [UIImage imageNamed:@"lock"];
  3674. }
  3675. // Directory con passcode lock attivato
  3676. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileNameData];
  3677. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  3678. if (metadata.directory && (directory.lock && [[CCUtility getBlockCode] length]))
  3679. cell.statusImageView.image = [UIImage imageNamed:@"passcode"];
  3680. // ----------------------------------------------------------------------------------------------------------
  3681. // Favorite
  3682. // ----------------------------------------------------------------------------------------------------------
  3683. if (metadata.favorite) {
  3684. cell.offlineImageView.image = [UIImage imageNamed:@"favorite"];
  3685. }
  3686. // ----------------------------------------------------------------------------------------------------------
  3687. // Share
  3688. // ----------------------------------------------------------------------------------------------------------
  3689. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3690. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3691. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3692. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3693. // Aggiungiamo il Tap per le shared
  3694. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3695. if (isShare) {
  3696. if (metadata.directory) {
  3697. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3698. cell.sharedImageView.userInteractionEnabled = NO;
  3699. } else {
  3700. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3701. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3702. [tap setNumberOfTapsRequired:1];
  3703. cell.sharedImageView.userInteractionEnabled = YES;
  3704. [cell.sharedImageView addGestureRecognizer:tap];
  3705. }
  3706. }
  3707. if (isMounted) {
  3708. if (metadata.directory) {
  3709. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] color:[NCBrandColor sharedInstance].brand];
  3710. cell.sharedImageView.userInteractionEnabled = NO;
  3711. } else {
  3712. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] color:[NCBrandColor sharedInstance].brand];
  3713. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3714. [tap setNumberOfTapsRequired:1];
  3715. cell.sharedImageView.userInteractionEnabled = YES;
  3716. [cell.sharedImageView addGestureRecognizer:tap];
  3717. }
  3718. }
  3719. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3720. if (metadata.directory) {
  3721. if ([shareLink length] > 0)
  3722. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] color:[NCBrandColor sharedInstance].brand];
  3723. if ([shareUserAndGroup length] > 0)
  3724. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3725. cell.sharedImageView.userInteractionEnabled = NO;
  3726. } else {
  3727. if ([shareLink length] > 0)
  3728. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareLink"] color:[NCBrandColor sharedInstance].brand];
  3729. if ([shareUserAndGroup length] > 0)
  3730. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3731. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3732. [tap setNumberOfTapsRequired:1];
  3733. cell.sharedImageView.userInteractionEnabled = YES;
  3734. [cell.sharedImageView addGestureRecognizer:tap];
  3735. }
  3736. }
  3737. } else {
  3738. cell.sharedImageView.userInteractionEnabled = NO;
  3739. }
  3740. // ----------------------------------------------------------------------------------------------------------
  3741. // downloadFile
  3742. // ----------------------------------------------------------------------------------------------------------
  3743. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3744. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:@"statusdownloadcrypto"];
  3745. else cell.statusImageView.image = [UIImage imageNamed:@"statusdownload"];
  3746. // sessionTaskIdentifier : RELOAD + STOP
  3747. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3748. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptaskcrypto"] forState:UIControlStateNormal];
  3749. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3750. cell.cancelTaskButton.hidden = NO;
  3751. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3752. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3753. cell.reloadTaskButton.hidden = NO;
  3754. }
  3755. // sessionTaskIdentifierPlist : RELOAD
  3756. if (metadata.sessionTaskIdentifierPlist != k_taskIdentifierDone) {
  3757. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3758. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3759. cell.reloadTaskButton.hidden = NO;
  3760. }
  3761. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3762. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3763. if (progress > 0) {
  3764. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3765. else cell.progressView.progressTintColor = [UIColor blackColor];
  3766. cell.progressView.progress = progress;
  3767. cell.progressView.hidden = NO;
  3768. }
  3769. // ----------------------------------------------------------------------------------------------------------
  3770. // downloadFile Error
  3771. // ----------------------------------------------------------------------------------------------------------
  3772. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3773. cell.statusImageView.image = [UIImage imageNamed:@"statuserror"];
  3774. if ([metadata.sessionError length] == 0)
  3775. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3776. else
  3777. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3778. }
  3779. }
  3780. // ----------------------------------------------------------------------------------------------------------
  3781. // uploadFile
  3782. // ----------------------------------------------------------------------------------------------------------
  3783. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3784. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:@"statusuploadcrypto"];
  3785. else cell.statusImageView.image = [UIImage imageNamed:@"statusupload"];
  3786. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetaskcrypto"] forState:UIControlStateNormal];
  3787. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetask"] forState:UIControlStateNormal];
  3788. cell.cancelTaskButton.hidden = NO;
  3789. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3790. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3791. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3792. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:@"statusstopcrypto"];
  3793. else cell.statusImageView.image = [UIImage imageNamed:@"statusstop"];
  3794. cell.reloadTaskButton.hidden = NO;
  3795. cell.stopTaskButton.hidden = YES;
  3796. } else {
  3797. if (metadata.cryptated)[cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptaskcrypto"] forState:UIControlStateNormal];
  3798. else [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3799. cell.stopTaskButton.hidden = NO;
  3800. cell.reloadTaskButton.hidden = YES;
  3801. }
  3802. // se non c'è una preview in bianconero metti l'immagine di default
  3803. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3804. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploaddisable"] color:[NCBrandColor sharedInstance].brand];
  3805. cell.labelTitle.enabled = NO;
  3806. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3807. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3808. if (progress > 0) {
  3809. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3810. else cell.progressView.progressTintColor = [UIColor blackColor];
  3811. cell.progressView.progress = progress;
  3812. cell.progressView.hidden = NO;
  3813. }
  3814. // ----------------------------------------------------------------------------------------------------------
  3815. // uploadFileError
  3816. // ----------------------------------------------------------------------------------------------------------
  3817. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3818. cell.labelTitle.enabled = NO;
  3819. cell.statusImageView.image = [UIImage imageNamed:@"statuserror"];
  3820. if ([metadata.sessionError length] == 0)
  3821. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3822. else
  3823. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3824. }
  3825. }
  3826. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3827. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3828. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3829. return cell;
  3830. }
  3831. - (void)setTableViewFooter
  3832. {
  3833. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3834. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3835. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3836. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3837. UIFont *appFont = [UIFont systemFontOfSize:12];
  3838. footerLabel.font = appFont;
  3839. footerLabel.textColor = [UIColor grayColor];
  3840. footerLabel.backgroundColor = [UIColor clearColor];
  3841. footerLabel.textAlignment = NSTextAlignmentCenter;
  3842. NSString *folders;
  3843. NSString *files;
  3844. NSString *footerText;
  3845. if (_sectionDataSource.directories > 1) {
  3846. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3847. } else if (_sectionDataSource.directories == 1){
  3848. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3849. } else {
  3850. folders = @"";
  3851. }
  3852. if (_sectionDataSource.files > 1) {
  3853. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3854. } else if (_sectionDataSource.files == 1){
  3855. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3856. } else {
  3857. files = @"";
  3858. }
  3859. if ([folders isEqualToString:@""]) {
  3860. footerText = files;
  3861. } else if ([files isEqualToString:@""]) {
  3862. footerText = folders;
  3863. } else {
  3864. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3865. }
  3866. footerLabel.text = footerText;
  3867. [footerView addSubview:footerLabel];
  3868. [self.tableView setTableFooterView:footerView];
  3869. }
  3870. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3871. {
  3872. NSString *textMessage;
  3873. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3874. // settiamo il record file.
  3875. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3876. // se non può essere selezionata deseleziona
  3877. if ([cell isEditing] == NO)
  3878. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3879. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3880. if (self.tableView.editing) {
  3881. [self setTitle];
  3882. return;
  3883. }
  3884. // test crash
  3885. NSArray *metadatas = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  3886. if (indexPath.row >= [metadatas count]) return;
  3887. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3888. // se è in corso una sessione
  3889. if ([_metadata.session length] > 0) return;
  3890. if (_metadata.errorPasscode) {
  3891. // se UUID è nil lo sta ancora caricando quindi esci
  3892. if (!_metadata.uuid) return;
  3893. // esiste un hint ??
  3894. NSString *hint = [[CCCrypto sharedManager] getHintFromFile:_metadata.fileName isLocal:NO directoryUser:app.directoryUser];
  3895. // qui !! la richiesta della nuova passcode
  3896. if ([_metadata.uuid isEqualToString:[CCUtility getUUID]]) {
  3897. // stesso UUID ... la password è stata modificata !!!!!!
  3898. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_same_device_different_passcode_hint_",nil), hint];
  3899. else textMessage = NSLocalizedString(@"_same_device_different_passcode_", nil);
  3900. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3901. [alertView show];
  3902. } else {
  3903. // UUID diverso.
  3904. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_hint_",nil), _metadata.nameCurrentDevice, hint];
  3905. else textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_",nil), _metadata.nameCurrentDevice];
  3906. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3907. [alertView show];
  3908. }
  3909. // chiediamo la passcode e ricarichiamo tutto.
  3910. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3911. viewController.delegate = self;
  3912. viewController.fromType = CCBKPasscodeFromPasscode;
  3913. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3914. viewController.passcodeInputView.maximumLength = 64;
  3915. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3916. viewController.inputViewTitlePassword = NO;
  3917. viewController.title = [NCBrandOptions sharedInstance].brand;
  3918. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3919. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  3920. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3921. [self presentViewController:navigationController animated:YES completion:nil];
  3922. }
  3923. // modello o plist con il title a 0 allora è andato storto qualcosa ... ricaricalo
  3924. if (_metadata.cryptated && [_metadata.title length] == 0) {
  3925. NSString* selector;
  3926. if ([_metadata.type isEqualToString: k_metadataType_template]) selector = selectorLoadModelView;
  3927. else selector = selectorLoadPlist;
  3928. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3929. return;
  3930. }
  3931. // se il plist è caricato ed è un modello aprilo
  3932. if ([_metadata.type isEqualToString:k_metadataType_template]) [self openModel:_metadata.model isNew:false];
  3933. // file
  3934. if (_metadata.directory == NO && _metadata.errorPasscode == NO && [_metadata.type isEqualToString: k_metadataType_file]) {
  3935. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3936. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3937. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  3938. } else {
  3939. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3940. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3941. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3942. }
  3943. }
  3944. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  3945. }
  3946. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3947. {
  3948. [self setTitle];
  3949. }
  3950. #pragma --------------------------------------------------------------------------------------------
  3951. #pragma mark ===== Synchronize Folder Cell =====
  3952. #pragma --------------------------------------------------------------------------------------------
  3953. - (void)synchronizeFolderGraphicsServerUrl:(NSString *)serverUrl animation:(BOOL)animation
  3954. {
  3955. BOOL cryptated = NO;
  3956. CCCellMain *cell;
  3957. for (NSString* fileID in _sectionDataSource.allRecordsDataSource) {
  3958. tableMetadata *recordMetadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3959. if (recordMetadata.directory == NO)
  3960. continue;
  3961. if ([[CCUtility stringAppendServerUrl:_serverUrl addFileName:recordMetadata.fileNameData] isEqualToString:serverUrl]) {
  3962. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:recordMetadata.fileID];
  3963. cell = (CCCellMain *)[self.tableView cellForRowAtIndexPath:indexPath];
  3964. cryptated = recordMetadata.cryptated;
  3965. break;
  3966. }
  3967. }
  3968. if (!cell)
  3969. return;
  3970. if (animation) {
  3971. NSURL *myURL;
  3972. if (cryptated)
  3973. myURL = [[NSBundle mainBundle] URLForResource: @"synchronizedcrypto" withExtension:@"gif"];
  3974. else
  3975. myURL = [[NSBundle mainBundle] URLForResource: @"synchronized" withExtension:@"gif"];
  3976. } else {
  3977. cell.synchronizedImageView.image = nil;
  3978. }
  3979. }
  3980. #pragma --------------------------------------------------------------------------------------------
  3981. #pragma mark ===== Navigation ====
  3982. #pragma --------------------------------------------------------------------------------------------
  3983. - (BOOL)shouldPerformSegue
  3984. {
  3985. // if background return
  3986. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  3987. if (self.view.window == NO)
  3988. return NO;
  3989. // Collapsed ma siamo già in detail esci
  3990. if (self.splitViewController.isCollapsed)
  3991. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  3992. // Video in esecuzione esci
  3993. if (_detailViewController.photoBrowser.currentVideoPlayerViewController.isViewLoaded && _detailViewController.photoBrowser.currentVideoPlayerViewController.view.window) return NO;
  3994. return YES;
  3995. }
  3996. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  3997. {
  3998. id viewController = segue.destinationViewController;
  3999. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  4000. tableMetadata *metadata;
  4001. if ([viewController isKindOfClass:[UINavigationController class]]) {
  4002. UINavigationController *nav = viewController;
  4003. _detailViewController = (CCDetail *)nav.topViewController;
  4004. } else {
  4005. _detailViewController = segue.destinationViewController;
  4006. }
  4007. if ([sender isKindOfClass:[tableMetadata class]]) {
  4008. metadata = sender;
  4009. [allRecordsDataSourceImagesVideos addObject:sender];
  4010. } else {
  4011. metadata = _metadata;
  4012. for (NSString *fileID in _sectionDataSource.allEtag) {
  4013. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  4014. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  4015. [allRecordsDataSourceImagesVideos addObject:metadata];
  4016. }
  4017. }
  4018. _detailViewController.metadataDetail = metadata;
  4019. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  4020. _detailViewController.dateFilterQuery = nil;
  4021. _detailViewController.isCameraUpload = NO;
  4022. [_detailViewController setTitle:metadata.fileNamePrint];
  4023. }
  4024. // can i go to next viewcontroller
  4025. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  4026. {
  4027. NSString *nomeDir;
  4028. if(self.tableView.editing == NO && _metadata.errorPasscode == NO){
  4029. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  4030. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  4031. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  4032. // SE siamo in presenza di una directory bloccata E è attivo il block E la sessione password Lock è senza data ALLORA chiediamo la password per procedere
  4033. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  4034. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  4035. viewController.delegate = self;
  4036. viewController.fromType = CCBKPasscodeFromLockDirectory;
  4037. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  4038. viewController.inputViewTitlePassword = YES;
  4039. if ([CCUtility getSimplyBlockCode]) {
  4040. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  4041. viewController.passcodeInputView.maximumLength = 6;
  4042. } else {
  4043. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  4044. viewController.passcodeInputView.maximumLength = 64;
  4045. }
  4046. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  4047. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  4048. viewController.touchIDManager = touchIDManager;
  4049. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  4050. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  4051. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  4052. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  4053. [self presentViewController:navController animated:YES completion:nil];
  4054. return;
  4055. }
  4056. if (_metadata.cryptated) nomeDir = [_metadata.fileName substringToIndex:[_metadata.fileName length]-6];
  4057. else nomeDir = _metadata.fileName;
  4058. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  4059. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  4060. if (viewController.isViewLoaded == false || viewController == nil) {
  4061. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  4062. viewController.isFolderEncrypted = _metadata.cryptated;
  4063. viewController.serverUrl = serverUrlPush;
  4064. viewController.titleMain = _metadata.fileNamePrint;
  4065. viewController.textBackButton = _titleMain;
  4066. // save self
  4067. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  4068. }
  4069. // OFF SearchBar
  4070. [viewController cancelSearchBar];
  4071. [self.navigationController pushViewController:viewController animated:YES];
  4072. }
  4073. }
  4074. @end