CCMain.m 250 KB

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